Skip to content

Instantly share code, notes, and snippets.

@chrispsn
Created July 3, 2018 13:31
Show Gist options
  • Save chrispsn/4d451e0ebe5600148c7c392f6281b251 to your computer and use it in GitHub Desktop.
Save chrispsn/4d451e0ebe5600148c7c392f6281b251 to your computer and use it in GitHub Desktop.
Making short functions
// ES5 hasn't got arrow functions, so we need another way to make short functions...
// Highest arity in a built-in I've found so far is 4, in Array.prototype.reduce:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)
function F(_){return Function('a','b','c','d','"use strict";return '+_)};
const sum = F("a+b"), product = F("a*b");
const A = [1, 2, 3, 4];
console.assert(A.reduce(F("a+b"),0) === 10);
console.assert(A.reduce(F("a*b"),1) === 24);
console.assert(A.map(F("a % 2 === 0")).reduce(sum,0) === 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment