Created
April 12, 2011 04:42
-
-
Save hans/914939 to your computer and use it in GitHub Desktop.
Haskell-esque `zip` and `zipWith`, ported to node.js / CoffeeScript
This file contains 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
zip = (arr1, arr2) -> | |
basic_zip = (el1, el2) -> [el1, el2] | |
zip_with basic_zip, arr1, arr2 | |
# I wrote two implementations of `zipWith`: one is iterative, and one is recursive. Feel free to do some benchmarks if you feel like it :) | |
# zip_with, iterative style | |
zip_with = (func, arr1, arr2) -> | |
min = Math.min arr1.length, arr2.length | |
ret = [] | |
for i in [0...min] | |
ret.push func(arr1[i], arr2[i]) | |
ret | |
# zip_with, recursive style | |
zip_with_recursive = (func, arr1, arr2) -> | |
return [] if arr1.length is 0 or arr2.length is 0 | |
el1 = arr1.shift() | |
el2 = arr2.shift() | |
ret_arr = zipWith func, arr1, arr2 | |
ret_arr.unshift func(el1, el2) | |
ret_arr | |
# very short (too short) test | |
assert = require 'assert' | |
test_zip = -> | |
assert.equal zip([1, 2, 3], [4, 5, 6]), [[1, 4], [2, 5], [3, 6]] | |
add = (el1, el2) -> el1 + el2 | |
assert.equal zip_with(add, [1, 2, 3], [4, 5, 6]), [5, 7, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment