Skip to content

Instantly share code, notes, and snippets.

@nooga
Last active June 1, 2020 20:45
Show Gist options
  • Save nooga/c7e697627b02ebb3264952125c19c376 to your computer and use it in GitHub Desktop.
Save nooga/c7e697627b02ebb3264952125c19c376 to your computer and use it in GitHub Desktop.
> Array.prototype.sort.call(x, (a,b) => { console.log(x); return a - b; })
{ '0': 2, '1': 1, '2': 0, '3': -1, '7': -2, '8': -3, length: 9 }
{ '0': 2, '1': 1, '2': 0, '3': -1, '7': -2, '8': -3, length: 9 }
{ '0': 2, '1': 1, '2': 0, '3': -1, '7': -2, '8': -3, length: 9 }
{ '0': 2, '1': 1, '2': 0, '3': -1, '7': -2, '8': -3, length: 9 }
{ '0': 2, '1': 1, '2': 0, '3': -1, '7': -2, '8': -3, length: 9 }
{ '0': -3, '1': -2, '2': -1, '3': 0, '4': 1, '5': 2, length: 9 }
> x = [2,1,0,-1,,,-2,-3]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
> Array.prototype.sort.call(x, (a,b) => { console.log(x); return a - b; })
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ -3, -2, -1, 0, 1, 2, <2 empty items> ]
// wtf V8
> x = [2,1,0,-1,,,-2,-3]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
> x.sort((a,b) => {console.log(x); return a - b; })
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
[ -3, -2, -1, 0, 1, 2, <2 empty items> ]
> x = [2,1,0,-1,,,-2,-3]
[ 2, 1, 0, -1, <2 empty items>, -2, -3 ]
> x.sort()
[ -1, -2, -3, 0, 1, 2, <2 empty items> ] // WTF
@ddrcode
Copy link

ddrcode commented Jun 1, 2020

according to JS spec (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf):

Because non-existent property values always compare greater than undefined property values, and undefined always
compares greater than any other value, undefined property values always sort to the end of the result, followed by nonexistent property values.

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