Skip to content

Instantly share code, notes, and snippets.

@gasi
Created June 9, 2011 09:46
Show Gist options
  • Save gasi/1016439 to your computer and use it in GitHub Desktop.
Save gasi/1016439 to your computer and use it in GitHub Desktop.
Sorting under the influence of `undefined`
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 } ]
# 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
@aseemk
Copy link

aseemk commented Jun 9, 2011

The robust output seems to be the same as the naive one. Is that indeed the case or was this just a typo? =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment