Zip And Partition Arrays

Combine parallel arrays into tuples and split a collection by predicate, with a zipLongest variant that pads short inputs.

JavascriptData Integrity

Code

snippet
export function zipArrays(...arrays) {
  if (arrays.length === 0) return [];
  const length = Math.min(...arrays.map((array) => array.length));
  const result = [];
  for (let index = 0; index < length; index += 1) {
    result.push(arrays.map((array) => array[index]));
  }
  return result;
}

export function zipLongest(fillValue = null, ...arrays) {
  const length = Math.max(0, ...arrays.map((array) => array.length));
  const result = [];
  for (let index = 0; index < length; index += 1) {
    result.push(arrays.map((array) => (index < array.length ? array[index] : fillValue)));
  }
  return result;
}

export function partitionArray(values, predicate) {
  if (!Array.isArray(values)) throw new TypeError("values must be an array");
  if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
  const truthy = [];
  const falsy = [];
  values.forEach((value, index) => {
    if (predicate(value, index, values)) truthy.push(value);
    else falsy.push(value);
  });
  return [truthy, falsy];
}