-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.ts
52 lines (50 loc) · 1.25 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
43
44
45
46
47
48
49
50
51
52
/**
* @packageDocumentation
* @module @tomato-js/shared
*/
import { isArray, isObject } from "./is-type";
import { ObjectType, Eachable } from "./types";
import { forEach } from "./for-each";
function mapArray(elements: any[], func: (k: any, v: any) => any) {
const arr: any[] = [];
forEach(elements, (key: any, value: any) => {
arr.push(func(key, value));
});
return arr;
}
function mapObject(elements: ObjectType<any>, func: (k: any, v: any) => any) {
const obj: ObjectType<any> = {};
forEach(elements, (key: any, value: any) => {
obj[key] = func(key, value);
});
return obj;
}
/**
* 遍历对象或数组,返回新对象或数组
*
* 脚本举例
* ```
* import { map } from '@tomato-js/shared'
* const obj = {
* a: 1,
* b: 2
* };
* const obj2 = {};
* const arr = [1,2,3,4,5];
* map(obj, (k, v) => (obj2[v] = k));
* map(arr, (k, v) => v=v+1);//[2,3,4,5,6]
* ```
*
* @param elements - 需要遍历的值
* @param func - 执行函数
*/
export function map(elements: Eachable<any>, func: (k: any, v: any) => any) {
if (!elements) {
return;
}
if (isArray(elements)) {
return mapArray(elements as Array<any>, func);
} else if (isObject(elements)) {
return mapObject(elements, func);
}
}