Skip to content

Commit 1119821

Browse files
akinocccantfu
andauthored
feat(array): isDeepEqual and uniqueBy (#24)
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
1 parent f8698cd commit 1119821

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

‎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
returnArray.from(newSet(array))
7070
}
7171

72+
/**
73+
* Unique an Array by a custom equality function
74+
*
75+
* @category Array
76+
*/
77+
exportfunctionuniqueBy<T>(array: readonlyT[],equalFn: (a: any,b: any)=>boolean): T[]{
78+
returnarray.reduce((acc: T[],cur: any)=>{
79+
constindex=acc.findIndex((item: any)=>equalFn(cur,item))
80+
if(index===-1)
81+
acc.push(cur)
82+
returnacc
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
thrownewError(message)
44
}
55
exportconsttoString=(v: any)=>Object.prototype.toString.call(v)
6+
exportconstgetTypeName=(v: any)=>{
7+
if(v===null)
8+
return'null'
9+
consttype=toString(v).slice(8,-1).toLowerCase()
10+
returntypeofv==='object'||typeofv==='function' ? type : typeofv
11+
}
612
exportconstnoop=()=>{}

‎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+
exportfunctionisDeepEqual(value1: any,value2: any): boolean{
4+
consttype1=getTypeName(value1)
5+
consttype2=getTypeName(value2)
6+
if(type1!==type2)
7+
returnfalse
8+
9+
if(type1==='array'){
10+
if(value1.length!==value2.length)
11+
returnfalse
12+
13+
returnvalue1.every((item: any,i: number)=>{
14+
returnisDeepEqual(item,value2[i])
15+
})
16+
}
17+
if(type1==='object'){
18+
constkeyArr=Object.keys(value1)
19+
if(keyArr.length!==Object.keys(value2).length)
20+
returnfalse
21+
22+
returnkeyArr.every((key: string)=>{
23+
returnisDeepEqual(value1[key],value2[key])
24+
})
25+
}
26+
returnvalue1===value2
27+
}

0 commit comments

Comments
 (0)