最佳答案
Given an ES6 Map and predicate function, how do I safely delete all non-matching elements for the map?
I could not find an official API function, but I can think of two implementations. The first does not attempt to delete in-place, but instead creates a copy:
// version 1:
function filter(map, pred) {
const result = new Map();
for (let [k, v] of map) {
if (pred(k,v)) {
result.set(k, v);
}
}
return result;
}
const map = new Map().set(1,"one").set(2,"two").set(3,"three");
const even = filter(map, (k,v) => k % 2 === 0);
console.log([...even]); // Output: "[ [ 2, 'two' ] ]"
The other deletes in-place. In my tests, it works but I did not find a guarantee that modifying a map does not break the iterator (of the for-of loop):
// version 2:
function deleteIfNot(map, pred) {
for (let [k, v] of map) {
if (!pred(k,v)) {
map.delete(k);
}
}
return map;
}
const map = new Map().set(1,"one").set(2,"two").set(3,"three");
deleteIfNot(map, (k,v) => k % 2 === 0);
console.log([...map]); // Output: "[ [ 2, 'two' ] ]"
Question: