79717802

Date: 2025-07-28 19:37:35
Score: 1
Natty:
Report link

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.

Reasons:
  • RegEx Blacklisted phrase (1.5): I'm new
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: David K. Storrs