@Juan Mendes
与内置地图相同,但效率更高(在查找附加值时)
function mapDelta(oldMap, newMap, compare) {
var delta = {
added: [],
deleted: [],
changed: []
};
var newKeys = new Set(newMap.keys());
oldMap.forEach(function (oldValue, oldKey) {
newKeys.delete(oldKey);
var newValue = newMap.get(oldKey);
if (newValue == undefined) {
delta.deleted.push({ key: oldKey, value: oldValue });
return;
}
else if (!compare(oldValue, newValue)) {
delta.changed.push({ key: oldKey, oldValue: oldValue, newValue: newValue });
}
});
newKeys.forEach(function (newKey) {
delta.added.push({ key: newKey, value: newMap.get(newKey) });
});
return delta;
}
并使用typescript
function mapDelta<K, T>(oldMap: Map<K, T>, newMap: Map<K, T>, compare: (a: T, b: T) => boolean) {
const delta = {
added: [] as { key: K, value: T }[],
deleted: [] as { key: K, value: T }[],
changed: [] as { key: K, oldValue: T, newValue: T }[]
};
const newKeys = new Set(newMap.keys());
oldMap.forEach((oldValue, oldKey) => {
newKeys.delete(oldKey);
const newValue = newMap.get(oldKey);
if (newValue == undefined) {
delta.deleted.push({ key: oldKey, value: oldValue });
return;
} else if (!compare(oldValue, newValue)) {
delta.changed.push({ key: oldKey, oldValue: oldValue, newValue: newValue });
}
})
newKeys.forEach((newKey) => {
delta.added.push({ key: newKey, value: newMap.get(newKey) });
})
return delta;
}