Skip to content

Instantly share code, notes, and snippets.

@forivall
Created March 5, 2014 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forivall/9375347 to your computer and use it in GitHub Desktop.
Save forivall/9375347 to your computer and use it in GitHub Desktop.
Simple (non-robust) Natural Sort in coffeescript
natcompare_re = /^(\D*)(\d*)([\s\S]*)$/
naturalCompare = (a, b) ->
return 0 if a is b
[__, a_word, a_num, a_rest] = natcompare_re.exec(a)
[__, b_word, b_num, b_rest] = natcompare_re.exec(b)
return (if a < b then -1 else 1) if a_word isnt b_word
return (+a_num) - (+b_num) if a_num isnt b_num
return naturalCompare a_rest, b_rest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment