Last active
August 29, 2015 14:22
-
-
Save murrayju/d399b2b9a542698417fd to your computer and use it in GitHub Desktop.
Using Array.prototype.sort to implement a stable sort
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
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