Making short functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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