Very late to the party on this one, but this thread is the top google result for 'javascript identity function' so I figured I'd chime in. I'm newish to Javascript, so hopefully I'm not simply unaware of a better solution.
I find this code useful:
function identity(a) { return a }
function makeCompare(key = identity, reverse = false) {
function compareVals(a, b) {
const keyA = key(a);
const keyB = key(b);
let result = keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
if ( reverse ) { result *= -1 }
return result;
}
return compareVals;
}
I can then sort arbitrary data structures in a tidy way:
const arrB = [ {name : "bob", age: 9}, {name : "alice", age: 7} ];
console.log(arrB.sort( makeCompare( val => { return val.age } )));
console.log(arrB.sort( makeCompare( val => { return val.age }, true)));
// output:
// Array [Object { name: "alice", age: 7 }, Object { name: "bob", age: 9 }]
// Array [Object { name: "bob", age: 9 }, Object { name: "alice", age: 7 }]
Note that this is dependent on having an 'identity' function to use as the default 'key' function.