lazy.js icon indicating copy to clipboard operation
lazy.js copied to clipboard

Feature request: zipWith()

Open rudijs opened this issue 11 years ago • 3 comments

Hi,

Does lazyjs support a zipWith() type function?

I've reviewed the API docs but, I may have overlooked it.

Something like this static zipWith example:

// JSON.stringify(Array.zip([1,2,3],[4,5,6], function(left, right) { return left + right })) === '[5,7,9]' accumulatedValue + currentValue; }); === [6];

Array.zip = function(left, right, combinerFunction) {
    var counter,
        results = [];

    for(counter = 0; counter < Math.min(left.length, right.length); counter++) {
        results.push(combinerFunction(left[counter],right[counter]));
    }

    return results;
};

rudijs avatar Nov 01 '14 02:11 rudijs

Currently, no. However it's worth pointing out that zip is really just a special case of map; and the same would be true of zipWith; i.e.:

function zipWith(left, right, combinerFn) {
  return Lazy(left).map(function(e, i) {
    return combinerFn(e, right[i]);
  });
}

Right?

If you feel this is a common enough special case to warrant its own method, I'm certainly open to it. Maybe you could provide some links to other functional libraries that include zipWith or something like it?

dtao avatar Nov 28 '14 17:11 dtao

@dtao ah ok .. interesting, I'm new to FP and just discovering the different approaches.

Zip being like a special case of map make sense to me, thanks for the example that's a great help.

As for examples of other libraries, ramda.js has zip and zipWith http://ramda.github.io/ramdocs/docs/R.html#zipWith

I was working though this tutorial, http://jhusain.github.io/learnrx/, which implements zip.

I then checked out lodash and underscore, also lazy.js.

I mentioned the zip notion here as I think I'll go with lazy for my code, again thanks for your feedback.

rudijs avatar Nov 30 '14 04:11 rudijs

zip and zipWith are also available in Haskell.

Important to note that zip and zipWith are not really limited to 2 arrays, one can zip multiple arrays together. For example:

var a = zipWith([[1,2,3], [4,5,6], [7,8,9]], (a,b,c) => a + b + c));
// [12, 15, 18]

niloy avatar Jan 11 '15 05:01 niloy