UNPKG

locutus

Version:

Locutus other languages' standard libraries to JavaScript for fun and educational purposes

29 lines (28 loc) 944 B
export function zipWithNext(values, transform) { // discuss at: https://locutus.io/kotlin/collections/zipWithNext/ // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Produces adjacent pairs or transformed adjacent values, like Kotlin zipWithNext. // example 1: zipWithNext([1, 2, 3, 4]) // returns 1: [[1, 2], [2, 3], [3, 4]] // example 2: zipWithNext([1, 2, 3, 4], (a, b) => b - a) // returns 2: [1, 1, 1] // example 3: zipWithNext(['a']) // returns 3: [] if (!Array.isArray(values) || values.length < 2) { return []; } const out = []; for (let i = 0; i < values.length - 1; i++) { const current = values[i]; const next = values[i + 1]; if (transform) { ; out.push(transform(current, next)); } else { ; out.push([current, next]); } } return out; }