Skip to content

Commit d7b8386

Browse files
committed
feat(zip): add zip function
1 parent 2ff0ed7 commit d7b8386

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

index.test.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ import {
4949
split,
5050
sum,
5151
tail,
52-
takeWhile
52+
takeWhile,
53+
zip
5354
} from "./index";
5455

5556
test("isArray", t => {
@@ -413,6 +414,14 @@ test("partitionWhile", t => {
413414
]);
414415
});
415416

417+
test("zip", t => {
418+
t.deepEqual(zip([1, 2, 3], [6, 5, 4, 3, 2, 1]), [
419+
[1, 6],
420+
[2, 5],
421+
[3, 4]
422+
]);
423+
});
424+
416425
test("keyBy", t => {
417426
const map = keyBy([1, 3, 4, 2, 5, 6], e => (e % 2 === 0 ? "even" : "odd"));
418427
t.deepEqual(map.get("even"), [4, 2, 6]);

index.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,29 @@ export function partitionWhileFn<T>(
785785
return array => partitionWhile(array, predicate);
786786
}
787787

788+
/** Takes two arrays and returns an array of corresponding pairs.
789+
*
790+
* If one of the supplied arrays is shorter than the other, then the excess
791+
* elements of the longer array will be discarded. */
792+
export function zip<T, U>(a: readonly T[], b: readonly U[]): Array<[T, U]> {
793+
const result: Array<[T, U]> = [];
794+
for (let i = 0; i < a.length && i < b.length; ++i) {
795+
result.push([a[i], b[i]]);
796+
}
797+
return result;
798+
}
799+
800+
/** Returns a function that combines the elements of `a` with the elements of
801+
* `b` and returns an array of corresponding pairs.
802+
*
803+
* If one of the supplied arrays is shorter than the other, then the excess
804+
* elements of the longer array will be discarded.
805+
*
806+
* This is the curried variant of {@link zip}. */
807+
export function zipFn<T, U>(b: readonly U[]): (a: readonly T[]) => Array<[T, U]> {
808+
return a => zip(a, b);
809+
}
810+
788811
export function keyBy<TKey, TElement>(
789812
array: ArrayLike<TElement>,
790813
f: (element: TElement, index: number) => TKey

0 commit comments

Comments
 (0)