-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter map.js
More file actions
31 lines (26 loc) · 923 Bytes
/
filter map.js
File metadata and controls
31 lines (26 loc) · 923 Bytes
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
/*
请你给原生的 Map 添加方法 filterKeys 和 filterValues,可以类似于于数组方法的 filter。它们分别可以对 Map 的键和值进行筛选,它们会返回一个新的 Map, 是对原有的 Map 的筛选结果,例如:
const m = new Map([['Jerry', 12], ['Jimmy', 13], ['Tomy', 14]])
m.filterKeys((key) => key.startsWith('J')) // => Map { Jerry => 12, Jimmy => 13 }
m.filterValues((val) => val >= 13) // => Map { Jimmy => 13, Tomy => 14 }
// 原有的 map 保持不变
console.log(m) // => Map { Jerry => 12 , Jimmy => 13, Tomy => 14 }
*/
Map.prototype.filterKeys = function(fn) {
const map = new Map();
for (let [key, value] of this) {
if (fn(key)) {
map.set(key, value)
}
}
return map;
}
Map.prototype.filterValues = function(fn) {
const map = new Map();
for (let [key, value] of this) {
if (fn(value)) {
map.set(key, value)
}
}
return map;
}