Skip to content

Instantly share code, notes, and snippets.

@murrayju
Last active August 29, 2015 14:22
Show Gist options
  • Save murrayju/d399b2b9a542698417fd to your computer and use it in GitHub Desktop.
Save murrayju/d399b2b9a542698417fd to your computer and use it in GitHub Desktop.
Using Array.prototype.sort to implement a stable sort
define [], () ->
Array.prototype.unstableSort = Array.prototype.sort
Array.prototype.sort = (compareFn) ->
compareFn ?= (a, b) -> a?.toString?()?.localeCompare?(b?.toString?()) || 0
list = ({ pos: i, val: v} for v, i in this)
list.unstableSort (a, b) ->
comp = compareFn(a.val, b.val)
return a.pos - b.pos if comp == 0
return comp
this[..] = (v.val for v in list)
return this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment