Skip to content

Instantly share code, notes, and snippets.

@joshburgess
Created February 11, 2018 21:19
Show Gist options
  • Save joshburgess/bd1d67c41be757d202b11c47c7e918fe to your computer and use it in GitHub Desktop.
Save joshburgess/bd1d67c41be757d202b11c47c7e918fe to your computer and use it in GitHub Desktop.
import compose from 'ramda/src/compose'
import equals from 'ramda/src/equals'
import filter from 'ramda/src/filter'
import head from 'ramda/src/head'
import length from 'ramda/src/length'
import map from 'ramda/src/map'
import min from 'ramda/src/min'
import not from 'ramda/src/not'
import sort from 'ramda/src/sort'
import split from 'ramda/src/split'
import toLower from 'ramda/src/toLower'
import uniq from 'ramda/src/uniq'
import zip from 'ramda/src/zip'
// imperative naturalCompare
const naturalCompareImperative = (a, b) => {
const NUMBER_GROUPS = /(-?\d*\.?\d+)/g
const splitOnNumGroups = compose(split(NUMBER_GROUPS), toLower, String)
const as = splitOnNumGroups(a)
const bs = splitOnNumGroups(b)
const asLength = length(as)
const bsLength = length(bs)
const minLength = min(asLength)(bsLength)
/* eslint-disable fp/no-loops */
/* eslint-disable fp/no-let */
/* eslint-disable fp/no-mutation */
let i = -1
while (++i < minLength) {
const x = as[i]
const y = bs[i]
if (x !== y) {
return x > y ? 1 : -1
}
}
return asLength > bsLength
? 1
: (asLength < bsLength ? -1 : 0)
/* eslint-enable fp/no-loops */
/* eslint-enable fp/no-let */
/* eslint-enable fp/no-mutation */
}
// functional naturalCompare
const naturalCompare = (a, b) => {
const NUMBER_GROUPS = /(-?\d*\.?\d+)/g
const splitOnNumGroups = compose(split(NUMBER_GROUPS), toLower, String)
const as = splitOnNumGroups(a)
const bs = splitOnNumGroups(b)
const asLength = length(as)
const bsLength = length(bs)
const pairs = zip(as)(bs)
const charCompare = ([x, y]) => x === y
? 0
: x > y ? 1 : -1
const notEqZero = compose(not, equals(0))
const results = compose(
filter(notEqZero),
map(charCompare),
)(pairs)
return length(results)
? head(results)
: (
asLength === bsLength
? 0
: asLength > bsLength ? 1 : -1
)
}
const naturalSort = sort(naturalCompare)
export default naturalSort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment