diff --git a/package.json b/package.json index 3ae4a99..2eb0370 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "web-utility", - "version": "4.7.0", + "version": "4.7.1", "license": "LGPL-3.0", "author": "shiy2008@gmail.com", "description": "Web front-end toolkit based on TypeScript", diff --git a/source/data.ts b/source/data.ts index 0733cee..32ebad5 100644 --- a/source/data.ts +++ b/source/data.ts @@ -134,14 +134,13 @@ export enum DiffStatus { } export function diffKeys(oldList: T[], newList: T[]) { + const oldSet = new Set(oldList), + newSet = new Set(newList); const map = {} as Record; - for (const item of oldList) map[item] = DiffStatus.Old; - - for (const item of newList) { - map[item] ||= 0; - map[item] += DiffStatus.New; - } + for (const item of oldSet.difference(newSet)) map[item] = DiffStatus.Old; + for (const item of oldSet.intersection(newSet)) map[item] = DiffStatus.Same; + for (const item of newSet.difference(oldSet)) map[item] = DiffStatus.New; return { map, diff --git a/test/data.spec.ts b/test/data.spec.ts index 819a7af..7a7d2bd 100644 --- a/test/data.spec.ts +++ b/test/data.spec.ts @@ -153,6 +153,17 @@ describe('Data', () => { }); }); + it('should ignore duplicate keys when comparing key arrays', () => { + expect(diffKeys(['a', 'a', 'b'], ['b', 'b', 'c', 'c'])).toEqual({ + map: { a: DiffStatus.Old, b: DiffStatus.Same, c: DiffStatus.New }, + group: { + [DiffStatus.Old]: [['a', DiffStatus.Old]], + [DiffStatus.Same]: [['b', DiffStatus.Same]], + [DiffStatus.New]: [['c', DiffStatus.New]] + } + }); + }); + it('should detect an Object whether is Array-like or not', () => { expect(likeArray(NaN)).toBe(false); expect(likeArray('a')).toBe(true);