New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Core fn: sort-by #63
Comments
This one is tricky. Whose sorting do we want to match, javascript's or clojurescript's? Comparing JS vs CLJS Sort
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
(defn ^number compare
[x y]
(cond
(identical? x y) 0
(nil? x) -1
(nil? y) 1
(number? x) (if (number? y)
(garray/defaultCompare x y)
(throw (js/Error. (str "Cannot compare " x " to " y))))
(satisfies? IComparable x)
(-compare x y)
:else
(if (and (or (string? x) (array? x) (true? x) (false? x))
(identical? (type x) (type y)))
(garray/defaultCompare x y)
(throw (js/Error. (str "Cannot compare " x " to " y)))))) And function defaultCompare(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
} ImplementationThe only real difference between the two implementations is the export function sort_by(keyFn, compFnOrColl, collIfCompFn = undefined) {
const compFn = collIfCompFn ? compFnOrColl : defaultCompare;
const coll = collIfCompFn ? collIfCompFn : compFnOrColl;
// sort mutates the array in place and so we need to spread it into a new
// array first
return [...iterable(coll)].sort((a, b) => compFn(keyFn(a), keyFn(b)));
} Whichever direction we go we should use that same compare function for the
function defaultCompare(a, b) {
// default js sort uses the same string conversion that
// template interpolation does, from what I can tell
const aString = `${a}`;
const bString = `${b}`;
if (aString > bString) return 1;
else if (aString < bString) return -1;
else return 0;
}
GotchasIn either case sparse arrays are an interesting problem. How do we want to deal with them? ConclusionI think it would pay off to add |
Added |
Implement
sort-by
See #22 for implementation details of sequence functions
The text was updated successfully, but these errors were encountered: