Skip to content

Instantly share code, notes, and snippets.

@gerhardberger
Created March 31, 2012 22:08
Show Gist options
  • Save gerhardberger/2268998 to your computer and use it in GitHub Desktop.
Save gerhardberger/2268998 to your computer and use it in GitHub Desktop.
zipWith function for JavaScript.
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)});}
@jordanjoewatson
Copy link

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)));
}

@okdewit
Copy link

okdewit commented Aug 23, 2018

@jordanjoewatson

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