Skip to content

Instantly share code, notes, and snippets.

@Chris927
Created May 3, 2016 06:46
Show Gist options
  • Save Chris927/38fa7ffef624f423056a93badb43837f to your computer and use it in GitHub Desktop.
Save Chris927/38fa7ffef624f423056a93badb43837f to your computer and use it in GitHub Desktop.
A riddle (for a code snippet session, maybe)
// a "generic" function doing some work for us (in this case, just multiply
// value with a factor `n`)
function times(value, n) {
return value * n;
}
// "higher order function" to generate more specific functions
function makeTimes(n) {
return function(value) {
return times(value, n);
}
}
// using the specific functions (just to demonstrate, all good)
const times3 = makeTimes(3);
const times7 = makeTimes(7);
console.log(times3(3), times7(3));
// we may want to do things "in bulk", i.e. generate multiple higher order
// functions "in one go"
// This first attempt is broken, why?
function makeTimesMultipleBroken(arrayOfNs) {
const result = [];
for (var i = 0; i < arrayOfNs.length; i++) {
result.push(function(value) {
return times(value, arrayOfNs[i]);
});
}
return result;
}
var someTimes = makeTimesMultipleBroken([ 4, 5 ]);
var times4 = someTimes[0], times5 = someTimes[1];
console.log(times4(3), times5(3));
// This second attempt works. Why?
function makeTimesMultiple(arrayOfNs) {
return arrayOfNs.map(function(n) {
return function(value) {
return times(value, n);
}
});
}
someTimes = makeTimesMultiple([ 4, 5 ]);
times4 = someTimes[0];
times5 = someTimes[1];
console.log(times4(3), times5(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment