Skip to content

Commit 1119821

Browse files
akinocccantfu
andauthored
feat(array): isDeepEqual and uniqueBy (#24)
Co-authored-by: Anthony Fu <[email protected]>
1 parent f8698cd commit 1119821

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

src/array.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,20 @@ export function uniq<T>(array: readonly T[]): T[] {
6969
return Array.from(new Set(array))
7070
}
7171

72+
/**
73+
* Unique an Array by a custom equality function
74+
*
75+
* @category Array
76+
*/
77+
export function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[] {
78+
return array.reduce((acc: T[], cur: any) => {
79+
const index = acc.findIndex((item: any) => equalFn(cur, item))
80+
if (index === -1)
81+
acc.push(cur)
82+
return acc
83+
}, [])
84+
}
85+
7286
/**
7387
* Get last item
7488
*

src/base.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,10 @@ export const assert = (condition: boolean, message: string): asserts condition =
33
throw new Error(message)
44
}
55
export const toString = (v: any) => Object.prototype.toString.call(v)
6+
export const getTypeName = (v: any) => {
7+
if (v === null)
8+
return 'null'
9+
const type = toString(v).slice(8, -1).toLowerCase()
10+
return typeof v === 'object' || typeof v === 'function' ? type : typeof v
11+
}
612
export const noop = () => {}

src/equal.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { getTypeName } from './base'
2+
3+
export function isDeepEqual(value1: any, value2: any): boolean {
4+
const type1 = getTypeName(value1)
5+
const type2 = getTypeName(value2)
6+
if (type1 !== type2)
7+
return false
8+
9+
if (type1 === 'array') {
10+
if (value1.length !== value2.length)
11+
return false
12+
13+
return value1.every((item: any, i: number) => {
14+
return isDeepEqual(item, value2[i])
15+
})
16+
}
17+
if (type1 === 'object') {
18+
const keyArr = Object.keys(value1)
19+
if (keyArr.length !== Object.keys(value2).length)
20+
return false
21+
22+
return keyArr.every((key: string) => {
23+
return isDeepEqual(value1[key], value2[key])
24+
})
25+
}
26+
return value1 === value2
27+
}

0 commit comments

Comments
 (0)