Created
June 9, 2011 09:46
-
-
Save gasi/1016439 to your computer and use it in GitHub Desktop.
Sorting under the influence of `undefined`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original | |
[ { id: 1, created: 300 }, | |
{ id: 2, created: 200 }, | |
{ id: 3, created: 500 }, | |
{ id: 4 }, | |
{ id: 5, created: 400 }, | |
{ id: 6, created: 100 }, | |
{ id: 7 } ] | |
Naive | |
[ { id: 2, created: 200 }, | |
{ id: 1, created: 300 }, | |
{ id: 3, created: 500 }, | |
{ id: 4 }, | |
{ id: 6, created: 100 }, | |
{ id: 5, created: 400 }, | |
{ id: 7 } ] | |
Robust | |
[ { id: 2, created: 200 }, | |
{ id: 1, created: 300 }, | |
{ id: 3, created: 500 }, | |
{ id: 4 }, | |
{ id: 6, created: 100 }, | |
{ id: 5, created: 400 }, | |
{ id: 7 } ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sort functions | |
naive = (a, b) -> | |
a.created - b.created | |
robust = (a, b) -> | |
r = a.created - b.created | |
if isNaN r | |
r = 0 | |
r | |
# List | |
list = [ | |
{id: 1, created: 300}, | |
{id: 2, created: 200}, | |
{id: 3, created: 500}, | |
{id: 4}, # missing key | |
{id: 5, created: 400}, | |
{id: 6, created: 100}, | |
{id: 7} # another missing key | |
] | |
# Original | |
console.log '\nOriginal' | |
console.log list | |
# Naive | |
console.log '\nNaive' | |
l2 = list.slice(0) | |
l2.sort naive | |
console.log l2 | |
# Robust | |
console.log '\nRobust' | |
l3 = list.slice(0) | |
l3.sort robust | |
console.log l3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The robust output seems to be the same as the naive one. Is that indeed the case or was this just a typo? =)