Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript is similar to Python's zip function


May 09, 2021 CoffeeScript


Table of contents


A zip function similar to Python

Problem

You want to connect multiple arrays together to generate an array of arrays. I n other words, you need to implement a function similar to the zip function in Python. Python's zip function returns an array of utons, each of which contains the first element in the array as an argument.

Solution

Use the following CoffeeScript code:

# Usage: zip(arr1, arr2, arr3, ...)
zip = () ->
  lengthArray = (arr.length for arr in arguments)
  length = Math.max.apply(Math, lengthArray)
  argumentLength = arguments.length
  results = []
  for i in [0...length]
    semiResult = []
    for arr in arguments
      semiResult.push arr[i]
    results.push semiResult
  return results

zip([0, 1, 2, 3], [0, -1, -2, -3])
# => [[0, 0], [1, -1], [2, -2], [3, -3]]