From 810ccc7c04a7ee926b2b922fd3374fe9d46e5cee Mon Sep 17 00:00:00 2001 From: "Alex A. Naanou" Date: Thu, 15 Oct 2020 03:12:42 +0300 Subject: [PATCH] added .zip(..) to Arrays... Signed-off-by: Alex A. Naanou --- Array.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 +++ package.json | 2 +- 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/Array.js b/Array.js index a279a8c..9ee90c0 100644 --- a/Array.js +++ b/Array.js @@ -16,6 +16,9 @@ /*********************************************************************/ + + + // Array.prototype.flat polyfill... // // NOTE: .flat(..) is not yet supported in IE/Edge... @@ -314,6 +317,49 @@ Array.prototype.toMap = function(normalize){ return m }, new Map()) } +// zip(array, array, ...) +// -> [[item, item, ...], ...] +// +// zip(func, array, array, ...) +// -> [func(i, [item, item, ...]), ...] +// +Array.zip = +function(func, ...arrays){ + var i = arrays[0] instanceof Array ? + 0 + : arrays.shift() + if(func instanceof Array){ + arrays.splice(0, 0, func) + func = null } + // build the zip item... + // NOTE: this is done this way to preserve array sparseness... + var s = arrays + .reduce(function(res, a, j){ + //a.length > i + i in a + && (res[j] = a[i]) + return res + }, new Array(arrays.length)) + return arrays + // check that at least one array is longer than i... + .reduce(function(res, a){ + return Math.max(res, i, a.length) }, 0) > i ? + // collect zip item... + [func ? func(i, s) : s] + // get next... + .concat(this.zip(func, i+1, ...arrays)) + // done... + : [] } +// XXX would be nice for this to use the instance .zip(..) in recursion... +// ...this might be done by reversign the current implementation, i.e. +// for instance .zip(..) to be the main implementation and for +// Array.zip(..) to be a proxy to that... +Array.prototype.zip = +function(func, ...arrays){ + return func instanceof Array ? + this.constructor.zip(this, func, ...arrays) + : this.constructor.zip(func, this, ...arrays) } + /********************************************************************** diff --git a/README.md b/README.md index aff7a6f..7d8eb7a 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ A library of JavaScript type extensions, types and type utilities. - [`.inplaceSortAs(..)`](#arrayinplacesortas) - [`.toKeys(..)`](#arraytokeys) - [`.toMap(..)`](#arraytomap) + - [`Array.zip(..)` / `.zip(..)`](#arrayzip--arrayzip) - [Large `Array` iteration (chunked)](#large-array-iteration-chunked) - [`.CHUNK_SIZE`](#arraychunk_size) - [`.mapChunks(..)`](#arraymapchunks) @@ -323,6 +324,8 @@ This will return `true` if: #### `.toMap(..)` +#### `Array.zip(..)` / `.zip(..)` + ### Large `Array` iteration (chunked) diff --git a/package.json b/package.json index 74f3151..f8c7ae7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ig-types", - "version": "2.0.16", + "version": "2.0.19", "description": "Generic JavaScript types and type extensions...", "main": "main.js", "scripts": {