Created
March 31, 2012 22:08
-
-
Save gerhardberger/2268998 to your computer and use it in GitHub Desktop.
zipWith function for JavaScript.
This file contains hidden or 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
zipWith = function() { | |
var args = Array.prototype.slice.call(arguments) | |
, ls = _.initial(args) | |
, ls_ | |
, f = _.last(args) | |
ls_ = _.zip.apply(this, ls) | |
ls_ = _.map(ls_, function(x) { | |
return f.apply(this, x) | |
}) | |
return ls_ | |
} | |
// Minified version | |
function zipWith(){var a=Array.prototype.slice.call(arguments),l=_.initial(a),f=_.last(a);return _.map(_.zip.apply(this,l),function(x){return f.apply(this,x)});} |
More concise:
zipWith = (f, xs, ys) => xs.map((n,i) => f(n, ys[i]))
Or if you prefer some curry:
zipWith = (f) => (xs) => (ys) => xs.map((n,i) => f(n, ys[i]))
At which point you might be tempted to do something like:
fibs = [1]
.concat([2])
.concat(zipWith ((x,y) => x+y) (fibs) (fibs.slice(1)) )
.slice(0, 10)
But Javascript is lacking lazy evaluation & infinite arrays of course.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm new to JS and found this a bit difficult to understand and read, I've written a shorter recursive version I find easier to understand that uses a lambda. Can use it like the Haskell zipWith (+) [1,2] [4,5] with zipWith(((x,y) => x+y),[1,2],[4,5])
function zipWith(λ,xs,ys) {
if(xs.length == 0) return []
else return [λ(xs[0],ys[0])].concat(zipWith(λ,xs.slice(1),ys.slice(1)));
}