Skip to content

Instantly share code, notes, and snippets.

@acenturyandabit
Created March 22, 2024 23:13
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 acenturyandabit/7af5f69c1b5512fdecc3d025db6f8e2c to your computer and use it in GitHub Desktop.
Save acenturyandabit/7af5f69c1b5512fdecc3d025db6f8e2c to your computer and use it in GitHub Desktop.
// Compare two tuples for array.sort(); i.e. returns 1 if first item is larger; 2 if second item is larger, using the < operator.
// Similar to the std::tie comparison in c++: https://bajamircea.github.io/coding/cpp/2017/03/10/std-tie.html
type Comparable = number | string;
const tupleCompare = (a: Comparable[], b: Comparable[]) => {
return a.reduce((prev, el, idx) => {
if (prev != 0) return prev;
else {
if (el > b[idx]) return 1;
else if (el < b[idx]) return -1;
else return 0;
}
}, 0)
}
// Type-free, minified version for javascript
const jTupleCompare = (a, b) => a.reduce((p, e, i) => (p != 0) ? p : (e > b[i] ? 1 : (e < b[i] ? -1 : 0)), 0);
// Tests / usage
const assertEquals = (test, expected) => (test == expected) ? console.log("OK") : console.log(`Expected ${expected}, got ${test}`);
const customStruct1 = {
prop1: 1,
prop2: 2,
prop3: 3
}
const customStruct2 = {
prop1: 1,
prop2: 3,
prop3: 1
}
// order as most important to least important
const tieCustomStruct = (struct) =>[struct.prop1, struct.prop2, struct.prop3]
assertEquals(tupleCompare(tieCustomStruct(customStruct1), tieCustomStruct(customStruct2)), -1)
assertEquals(jTupleCompare(tieCustomStruct(customStruct1), tieCustomStruct(customStruct2)), -1)
assertEquals(tupleCompare(tieCustomStruct(customStruct2), tieCustomStruct(customStruct1)), 1)
assertEquals(jTupleCompare(tieCustomStruct(customStruct2), tieCustomStruct(customStruct1)), 1)
assertEquals(tupleCompare(tieCustomStruct(customStruct1), tieCustomStruct(customStruct1)), 0)
assertEquals(jTupleCompare(tieCustomStruct(customStruct1), tieCustomStruct(customStruct1)), 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment