-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathzipWith.ts
65 lines (55 loc) · 2.02 KB
/
zipWith.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type { PH } from './utils/types.ts';
import curryN from './utils/curry_n.ts';
// @types
type ZipWith_1<T1, T2> = <R>(fn: (a: T1, b: T2) => R) => R[];
type ZipWith_2<T1, R> = (list1: T1[]) => R[];
type ZipWith_3<T2, R> = (list2: T2[]) => R[];
type ZipWith_2_3<T1, T2, R> =
& ((list1: T1[]) => ZipWith_3<T2, R>)
& ((
list1: PH,
list2: T2[],
) => ZipWith_2<T1, R>)
& ((list1: T1[], list2: T2[]) => R[]);
type ZipWith_1_3<T1> =
& (<T2, R>(fn: (a: T1, b: T2) => R) => ZipWith_3<T2, R>)
& (<T2>(fn: PH, list2: T2[]) => ZipWith_1<T1, T2>)
& (<T2, R>(fn: (a: T1, b: T2) => R, list2: T2[]) => R[]);
type ZipWith_1_2<T2> =
& (<T1, R>(fn: (a: T1, b: T2) => R) => ZipWith_2<T1, R>)
& (<T1>(fn: PH, list1: T1[]) => ZipWith_1<T1, T2>)
& (<T1, R>(fn: (a: T1, b: T2) => R, list1: T1[]) => R[]);
type ZipWith =
& (<T1, T2, R>(fn: (a: T1, b: T2) => R) => ZipWith_2_3<T1, T2, R>)
& (<T1>(fn: PH, list1: T1[]) => ZipWith_1_3<T1>)
& (<T2>(fn: PH, list1: PH, list2: T2[]) => ZipWith_1_2<T2>)
& (<T1, T2, R>(fn: (a: T1, b: T2) => R, list1: T1[]) => ZipWith_3<T2, R>)
& (<T1, T2, R>(
fn: (a: T1, b: T2) => R,
list1: PH,
list2: T2[],
) => ZipWith_2<T1, R>)
& (<T1, T2>(fn: PH, list1: T1[], list2: T2[]) => ZipWith_1<T1, T2>)
& (<T1, T2, R>(fn: (a: T1, b: T2) => R, list1: T1[], list2: T2[]) => R[]);
function _zipWith<T1, T2, R>(
fn: (a: T1, b: T2) => R,
list1: T1[],
list2: T2[],
) {
const len = Math.min(list1.length, list2.length);
const result = new Array<R>(len);
for (let i = 0; i < len; i++) {
result[i] = fn(list1[i], list2[i]);
}
return result;
}
/**
* Creates a new list out of two passed lists `list1`, `list2`.
* Each item of new list is calculated by applying equally-positioned pair
* in both the lists.
* The returned is truncated to the length of the shorter of the two input lists.
*
* Fae.zipWith(Fae.add, [100, 200, 300], [1, 2, 3]) // [101, 202, 303]
*/
export const zipWith = curryN(3, _zipWith) as ZipWith;