Edd Mann Developer

Lifting JavaScript operators into First-class Functions

I have always enjoyed how succinctly you are able to use commonly found operators as first-class functions in languages such as Clojure. As a quick thought experiment I decided to see if it would be possible to use JavaScript’s capabilities to dynamically create functions, to mimic such behaviour. This experiment resulted in the code you see below, permitting the lifting of operators into functions which can be passed around and used as expected.

let assoc = (ops, fn) =>
    .split(' ')
    .reduce((obj, op) => { obj[op] = fn(op); return obj; }, {});

let infix = assoc('+ - * /', op => Function('a', 'b', `return a ${op} b`));
let prefix = assoc('! ++ --', op => Function('a', `return ${op} a`));
let postfix = assoc('()', op => Function('a', `return a ${op}`));

let ƒ = (op) => infix[op] || prefix[op] || postfix[op];

[1, 2, 3, 4].reduce(ƒ('+'));