-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmap.ts
42 lines (31 loc) · 1.23 KB
/
map.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
import {isArrayLike} from './internal/array'
import {baseIteratee} from './internal/baseIteratee'
import isArray from './isArray'
import type {ListIterator} from './internal/baseIteratee.type'
function arrayMap<T, R>(array: ArrayLike<T> | null | undefined, iteratee: ListIterator<T, R>): R[] {
if (!array || array.length === 0) {
return []
}
const length = array.length
const result: R[] = new Array<R>(length)
for (let index = 0; index < length; index++) {
result[index] = iteratee(array[index], index, array)
}
return result
}
function baseMap<T, R>(array: ArrayLike<T> | null | undefined, iteratee: ListIterator<T, R>): R[] {
if (!array || array.length === 0) {
return []
}
const length = array.length
const result: R[] = isArrayLike(array) ? Array(array.length) : []
for (let index = 0; index < length; index++) {
result[index] = iteratee(array[index], index, array)
}
return result
}
export function map<T, R>(collection: ArrayLike<T> | null | undefined, iteratee: ListIterator<T, R>): R[] {
const mapper = isArray(collection) ? arrayMap : baseMap
return mapper(collection, baseIteratee(iteratee)) // 타입 일치 보장
}
export default map