Skip to content

Commit cf12bb2

Browse files
feat: add array zip algorithm
1 parent 5c39e87 commit cf12bb2

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

‎Data-Structures/Array/Zip.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function zip
3+
* @description Creates an array of grouped elements where the first element
4+
* contains the first elements of the given arrays, the second element
5+
* contains the second elements, and so on.
6+
* @param {...Array} arrays - Two or more arrays to zip together
7+
* @returns {Array} - Array of grouped elements
8+
* @see https://en.wikipedia.org/wiki/Convolution_(computer_science)
9+
* @example zip([1, 2], ['a', 'b']) => [[1, 'a'], [2, 'b']]
10+
* @example zip([1, 2, 3], ['a', 'b', 'c'], [true, false, true]) => [[1, 'a', true], [2, 'b', false], [3, 'c', true]]
11+
*/
12+
const zip = (...arrays) => {
13+
if (arrays.length === 0) {
14+
throw new TypeError('At least one array must be provided')
15+
}
16+
if (!arrays.every((arr) => Array.isArray(arr))) {
17+
throw new TypeError('All arguments must be arrays')
18+
}
19+
const minLength = Math.min(...arrays.map((arr) => arr.length))
20+
return Array.from({ length: minLength }, (_, i) =>
21+
arrays.map((arr) => arr[i])
22+
)
23+
}
24+
25+
export { zip }
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { zip } from '../Zip.js'
2+
3+
describe('zip', () => {
4+
test("zip([1,2],['a','b']) returns [[1,'a'],[2,'b']]", () => {
5+
expect(zip([1, 2], ['a', 'b'])).toEqual([
6+
[1, 'a'],
7+
[2, 'b']
8+
])
9+
})
10+
11+
test('zip three arrays', () => {
12+
expect(zip([1, 2], ['a', 'b'], [true, false])).toEqual([
13+
[1, 'a', true],
14+
[2, 'b', false]
15+
])
16+
})
17+
18+
test('zip truncates to shortest array', () => {
19+
expect(zip([1, 2, 3], ['a', 'b'])).toEqual([
20+
[1, 'a'],
21+
[2, 'b']
22+
])
23+
})
24+
25+
test('zip single array returns array of single element arrays', () => {
26+
expect(zip([1, 2, 3])).toEqual([[1], [2], [3]])
27+
})
28+
29+
test('zip with empty array returns empty array', () => {
30+
expect(zip([], [1, 2, 3])).toEqual([])
31+
})
32+
33+
test('zip does not mutate original arrays', () => {
34+
const arr1 = [1, 2]
35+
const arr2 = ['a', 'b']
36+
zip(arr1, arr2)
37+
expect(arr1).toEqual([1, 2])
38+
expect(arr2).toEqual(['a', 'b'])
39+
})
40+
41+
test('throws TypeError when no arguments provided', () => {
42+
expect(() => zip()).toThrow(TypeError)
43+
})
44+
45+
test('throws TypeError for non-array argument', () => {
46+
expect(() => zip([1, 2], 'ab')).toThrow(TypeError)
47+
})
48+
})

0 commit comments

Comments
 (0)