JavaScript: Sort object by a value

Actually the headline is not really what I want to say :-). But I don’t know any better yet.
I just want to write down how I solved sorting the following:

>>> var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000,
    helicopter:400, rocket:8*60*60}

This is a list of vehicles with their (approx.) max speeds. And now, I would like a list of the vehicles sorted by their max speed. This looks sooo easy, and actually it is :-). You just have to know how.
Look at this:

>>> var sortable = [];
>>> for (var vehicle in maxSpeed)
      sortable.push([vehicle, maxSpeed[vehicle]])
>>> sortable.sort(function(a, b) {return a[1] - b[1]})
[["bike", 60], ["motorbike", 200], ["car", 300],
["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Since the sort function takes an extra argument, that allows to do your custom comparison we simply make sure that the right stuff gets compared, which is our speed. Unfortunately we can not sort the object directly, it has to be an array for doing so. But you can now convert it back, or just extract the vehicles, like so:

>>> dojo.require("dojox.lang.functional")
>>> vehiclesSortedBySpeed =
        dojox.lang.functional.map(sortable, function(i) {return i[0]})
["bike", "motorbike", "car", "helicopter", "airplane", "rocket"]

Didn’t I say it was easy?

Comments (8)

JavaScript: Remove element from Array

[UPDATE] Thanks to Joe and others hinting me to the danger of purely using indexOf() without a check for -1. Added it in the last example.

I mean it’s not the first time I am doing it, but it happens always again that I have to look up how exactly it works. And every time I know it is very easy.
So here is how to remove an element from an array, mainly for my poor brain, so it doesn’t have to remember anymore. Though I know, now that I wrote it down I will never forget it again.

DON’T
Unfortunately the most obvioous solution leaves a “hole” in the array :-(.

>>> var list = [4,5,6];
>>> delete list[1];
true
>>> list
[4, undefined, 6]

Sad, but understandable.

DO
So do it right and use splice().

>>> var list = [4,5,6];
>>> list.splice(1, 1); // Remove one element, returns the removed ones.
[5]
>>> list
[4, 6]

Useful DO
Actually, what I mostly need is: remove a certain value from an array.
I.e. I have some list of visible IDs and I want to remove one because it’s not visible anymore. So just extend the above example a bit.

>>> var visibleIds = [4,5,6];
>>> var idx = visibleIds.indexOf(5); // Find the index
>>> if(idx!=-1) visibleIds.splice(idx, 1); // Remove it if really found!
[5]
>>> visibleIds
[4, 6]

I hope I didn’t bore anyone with that :-)

Comments (58)

Dojo.cast()

Now there is already episode 2 out of the dojo podcast “from the guys” (I like when Pete says that).
There we are trying to discuss common topics, interesting things about and around dojo. If you want to join us, have comments, an interesting story to tell or alikes, just let us know and mail us at wolfram@dojotoolkit.org or contact us in the irc channel #dojo (just ping one of us: phiggins, nonken or mccain).
Have fun listening …

Comments

Using FileMerge.app with Mercurial

I was looking for a nice GUI for Mercurial (and there are some), which I basically want for seeing nicer diffs. After searching a while I did come across something. In the Mercurial wiki I then found Using FileMerge.app/opendiff as the diff program (OS X). Pooh that is much better now :-).

Commiting more often
During the couple hours I was using Mercurial without having a nice diff tool I realized, that the “merge often” strategy also helps a little here. And if I understodd this right, that is the usual way when working with a distributed version control system, which also implies why they have to be faster in doing their operations.
If you just commit much sooner, say after you have finished a bigger train of thought (the drcs-way, if I got that right), instead of after having the entire task done (my usual svn way), then you also don’t need the diff tool that often. I am still used to diffing before every commit and just making sure I left no debug stuff in there and simply to be confident about the checkin. May be this is a bit old-fashioned and I should just really double-check by inspecting the diffs thouroughly when the before mentioned big task is done and I want to push it back to the incoming repositiory or distribute it in some other way.

My way to the distributed version control systems
After having ignored the distributed version control systems for a while I finally started using them, when the number of parallel patches and changes just overwhelmed me. And I realized it to be especially helpful when the revision control system that the client is using is not reachable over the web, just via intranet and you still have to work in some other place and want to checkin at times.
Actually I was interested in this stuff already for a while and first heard about it from Jan in 2006 (he suggested svk, by then I completely rejected the idea, because I didn’t see the necessity I guess) and some time later I got reminded of it again when I saw the much talked about video from Linus Torvald’s talk about git (which in some parts I find a bit too bold).
And finally today when I was listening to Scott Hanselman’s excellent show (excellent as usual, great job Scott, you are so enduring and have always interesting shows, keep it up) Distributed Source Control with Git all barriers finally came down and I have fully fallen for it.

Welcome to the real world

Comments

Dojo summer of code projects

I have just seen that there are some nice things to get tackled in the summer of code, I am really looking forward to the results of what will become some nice extensions.
Especially the drag+drop form editor and the intuitive animations toolkit will be two things that will make dojo even more popular and easier to use.
All the best you guys and have a great summer …

Comments

When the browser knows where you are

… we will be able to deliver much quicker, much cooler applications to the user. No installation needed, just an online connection. Not that I was not already talking about that for a while, but there was no hook between the position that your device knows and the web app you are running. Google Geear LocationAPI will provide it. It’s great to see the technologies go the right way to really provide the power to enable easier writing of really good apps. Let’s see what people come up with …
Btw, watch this video it is very nice in showing what gears is good for and what is yet to come, and you can hear dojo over and over again :-)!

Comments

Dojo meetup Europe 2008, in Berlin

Thanks to Nikolai Onken (the guy behind dojocampus.org), who is pushing to meet in Europe, we have decided to use LinuxTag 2008 and gather in Berlin this year.

dojo.explore("Berlin", "Saturday May 31, 2008 at 3pm");
dojo.beer();
dojo.dinner();
notTooTired = true;
while (notTooTired) {
    dojo.clubbing();
}

We will meet about 15:00 in the center of Berlin and will not let anyone go until midnight :-). Dojo meetup in Berlin, walk, talk drink and dance. So let’s do the first Dojo meetup Europe 2008 there will be more to come. Of course you can join anytime and any place, just keep in touch (i.e. on freenode.net in #dojo or on the dojo-interest mailing list) and you will get to know where and when.

Stay updated via the upcoming event page.

Comments (5)

Dojo really helps

There is a ton of helpful stuff in dojo and it is getting a lot better and more. Even the documentation is becoming better, so don’t hesitate to try it out! And there are some little pieces that you see coming every day that are being added to dojo to help.

There is for one the daily (if not hourly) progressing API viewer.
And there is the new dojox.help stuff.
And as a tiny little bit I also have added a piece (the apropos command) that probably gets added into the dojox.help namespace.

Stay on the pulse of dojo!

Comments

A functional task, I am sure

Now that I dove into functional programming (only using dojo and python, but it’s a start) and feel that my brain has not completely made the switch yet, I come across problems that look like they are best to be solved with functional programming. Isn’t it always that way, when you have started something new and are still excited about it, that the every day problems seem that they want to be solved the new way? Anyway, here it goes.

I got this dictionary. The keys are IDs and the values are kind of a rank. Now I want to sort the IDs by their rank.
I am sure there is a simple one liner for that. But I didn’t come up with it yet.
I only came up with a quite dumb concat, sort and split solution. Not elegant at all.


d = {4: 6, 12: 4, 14: 14, 18: 16, 32: 6,
    33: 24, 40: 27, 41: 6, 44: 25, 106: 2}
d1 = ["%06d" % v+'_'+str(k) for k,v in d.items()]
# d1 is now something like this:
# ['000006_4', '000004_12', '000014_14', '000016_18', ...]
d1.sort() # That allows us to sort, which does it
sorted = [int(i.split("_")[1]) for i in d1 ]

This has several drawbacks, but it was as good as I got :-(.
I hope this has no negative effect on my career.

[Update] Thanks to Daniel’s second post, this is the solution!


sorted(d.items(), key=itemgetter(1))

Awesome, thanks!

Comments (5)

It seems to be a Firebug Bug

After reporting the mentioned bug to the Firefox guys they were not able to confirm it, and they are right!
It seems to be a Firebug bug!
Because if I do the same tests inline in the Firebug Lite console (not the Firefox extension in the browser!) everything works as expected.


>>> [] instanceof Array
true

I keep investigating

Comments (1)

Firefox3 beta3 has a strange Array behaviour

See Alex’s blog entry he posted the problem with Firefox3 beta3!
In short


>>> typeof []
"object"
>>> var a = [];
>>> var b = new Array();
>>> a.constructor == b.constructor
false
>>> c = [];
[]
>>> c.constructor == a.constructor
true
>>> d = new Array();
[]
>>> b.constructor == d.constructor;
true
>>> b.constructor == a.constructor;
false

After reading Eugene’s article about functional fun with dojo I wanted to play with dojox.lang.functional, and got stuck right away on one of the first calls.


>>> dojo.require("dojox.lang.functional")
>>> dojo.require("dojox.lang.functional.fold")
>>> df = dojox.lang.functional
>>> df.reduce([1,2,3], "+")
TypeError: a.hasNext is not a function

Oops, that was not what I expected, thanks to Alex’s help Firefox3 beta3 could be identified as the one who causes the problem. And I filed a bug there, so lets hope the next Firefox beta/version does it right.

[Update] The bug seems to be in FireBug, not in Firefox

Comments (1)

dojox.widget.Rating commited

Yesterday another one of my contributions found it’s way into dojo: dojox.widget.Rating. You can try out the always latest version online in the dojo archive. It’s quite a simple form widget, that allows you to click a star for rating an item. The number of stars and the styling can be adjusted via images and CSS.
If you want an even more flexible way to customize the stars you should look at what Tobi has to offer with his SVG generated stars, they come in many more flavors!
ratingscreen.jpg

Comments (5)

Python is still awesome

Just because I just came across it while optimizing some old code, I have to mention this.
I have the following list of dictionaries (array or hash-arrays in other words) and I want to sum up the values of one of the items of the dictionary.

In python I do this


    d = [{'value':1, 'title':'one'}, {'value':2}, {'value':3},
         {'value':4, 'title':'four'}, ]
    s = sum([i['value'] for i in d])

In PHP I would have done this (I guess)


    function extract_value($r) {
        return $r['value'];
    }
    $d = array(array('value'=>1, 'title'=>'one'), array('value'=>2),
               array('value'=>3), array('value'=>4, 'title'=>'four'));
    $s = array_sum(array_map("extract_value", $d));

Cracks come forward and shorten it please (in any language!).

Comments (28)

JavaScript is programming!

I know that already for a long time. And since using dojo I know it even better. And already for a couple of years I am always again coming across functional programming, but never got any deeper into it then using the basic things. But now there is a really juicy piece of fruit I will chew, thanks to Eugene Lazutkin who wrote this wonderful article on Functional JavaScript fun in Dojo. And he also describes what which JS version implements, and more important which browser provides what. Must read!
Thanks …

Comments

Dojo demo engine

Ok, watch out for dojo accelerating and passing on the left … Shane O’Sullivan posted, already in december last year about the dojo demo engine. A great step forward and a way to document stuff much better, since you get examples and one tab further you see how it is coded.

demo_framework.jpg

It is still in development, but the future looks bright!
So, use all the resources you get …

Comments

Mayflower Barcamp - awesome!

Mayflower had invited me to join their Barcamp last weekend - and it was awesome. Thank you a lot!!!
We had been a crowd of about 40 people all hacking all day long until deep at night, it was a great atmosphere and some very interesting projects had been made. I am sure some things will come up on the Mayflower blog soon, just keep watching!
I was mainly working on integrating the dojo.grid into the next version of Phprojekt and doing some ground work for a very flexible structure. And I have learned a lot more about dojo again. It’s just great!
Besides that I was advocating a lot for Python and Django especially :-), I just can’t hold back. But it’s hard to convert anyone there, since Mayflower is the biggest and best PHP service provider in Germany and the people there are really good in what they are doing! Though one came up to me and said “thank you for putting the Python book on the table” (which I did a while ago in the Mayflower office, just for fun).
Thanks again and hopefully see you soon again.

Comments

Django’s dev server and UTF-8

From time to time I got this UnicodeEncodeError, but I had done all the things (sitecustomize.py, some more) right in order to configure the system in UTF-8. I thought.

I did the usual

     ./manage runserver

and since I assumed that on my Mac everything is already properly configured to be UTF-8 I didn’t even think of the shell not being properly set up. Fortunately my colleague Tobi found out that I have to set the shell variable LANG=”utf-8″. So now I always do:

     export LANG="utf-8"
     ./manage runserver

So I went from the wrong locale output to the one working properly with UTF-8 and Django, jiha!

cain@home:~> locale
LANG=
...
cain@home:~> export LANG="utf-8"
cain@home:~> locale
LANG="utf-8"
...
cain@home:~> # now i can safely start Django :-)
cain@home:~> ./manage runserver

Comments (8)

json_encode() updated

[UPDATE] The link to the sourcecode now points to the dojango implementation, the dpaste one is gone.

Just in case someone is using json_encode() I wrote a while ago, I have updated the function due to updates in the latest Django dev version. Find the source here.

I have solved two problems here. One is that now lazy strings are used all over in Django, which this updates handles and detecting a list and a dictionary stumbled on subclasses of them.

Comments (5)

Terminal background color per server

I just changed the config of my application and tested it if it still works, since I only switched DB names. Everything is cool. It works, all the pages show the same stuff it seems to work. Great thing!
A couple minutes later, I go to the shell window where I did that change and am wondering what server I am on. Geeeeeeee, the online version. I changed the DB to use on the live version. God damn it.

It was no big deal, since I hadn’t restarted the server yet, since my local dev server (django) automatically restarts when I change any python file. So I just undid the change online.
Something has to change that this won’t happen again, searching the web a bit and with the help of Daniel I found this article “Colorful Terminal”, where he had solved the same problem. Great solution.
Just one little thing, when I accidently forget to start the script which logs me into the server and changes the background color of my terminal … what then? Can the script not trigger on “ssh me@server.com”? Any ideas?

Comments (3)

Nice hardware mash-up

I just found eye-fi via the Sitepen blog. Just mix wifi and a flash card and you got more spare time and less cables hanging around. Cool.

Comments (3)