Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created April 30, 2018 00:30
Show Gist options
  • Save christianscott/a85521f53e5e4e343ca604e422a6a211 to your computer and use it in GitHub Desktop.
Save christianscott/a85521f53e5e4e343ca604e422a6a211 to your computer and use it in GitHub Desktop.
Higher order functions for iterating over arrays
function callWith() {
const args = arguments
return function (fn) {
return fn.apply(null, args)
}
}
const add = d => x => x + d
const updaters = [add(1), add(2), add(3)]
console.log(updaters.map(callWith(10))) // [11, 12, 13]
function callMethod(methodName) {
const args = Array.prototype.slice.call(arguments, 1)
return function (instance) {
return instance[methodName].apply(instance, args)
}
}
function Foo(x) {
if (!(this instanceof Foo)) {
return new Foo(x)
}
this.x = x
}
Foo.prototype.deltaX = function deltaX(d) {
return this.x + d
};
const instances = [Foo(1), Foo(2), Foo(3)]
console.log(instances.map(callMethod('deltaX', 10))) // [11, 12, 13]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment