Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Created November 3, 2012 07:16
Show Gist options
  • Select an option

  • Save hughfdjackson/4006400 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/4006400 to your computer and use it in GitHub Desktop.
var unnamed = function(){
var fns = [].slice.call(arguments);
return function(){
var args = [].slice.call(arguments);
return fns.map(function(fn){ return fn.apply(null, args) })
}
}
var sq = function(n){ return n * n },
double = function(n){ return n * 2 }
unnamed(sq, double)(3)
@FireyFly
Copy link
Copy Markdown

FireyFly commented Nov 3, 2012

You could take another approach and implement a flipped function application and then just use the regular Array#map, like so:

function callWith(x) {
  // already curried, for convenience
  return function (f) { return f(x) }
}

[sq, double].map(callWith(3))

(i.e. like in Haskell: map [sq, double] ($ 3))

@hughfdjackson
Copy link
Copy Markdown
Author

oOo that's a far nicer way to implement it. I see this as a general-purpose utility. As map, filter, etc do so elegantly, it could do with a function that describes what it does awesomely.

Copy link
Copy Markdown

ghost commented Nov 4, 2012

I agree, that looks much nicer. callWith is basically identical to flip ($) in Haskell. And (flip ($)) 3 is the same as ($ 3), since right sections basically do a flip.

Minor note, @FireyFly, you have map's parameters flipped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment