Skip to content

Commit

Permalink
feat(array): isDeepEqual and uniqueBy (#24)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
akinocccc and antfu committed Nov 29, 2022
1 parent f8698cd commit 1119821
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/array.ts
Expand Up @@ -69,6 +69,20 @@ export function uniq<T>(array: readonly T[]): T[] {
return Array.from(new Set(array))
}

/**
* Unique an Array by a custom equality function
*
* @category Array
*/
export function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[] {
return array.reduce((acc: T[], cur: any) => {
const index = acc.findIndex((item: any) => equalFn(cur, item))
if (index === -1)
acc.push(cur)
return acc
}, [])
}

/**
* Get last item
*
Expand Down
6 changes: 6 additions & 0 deletions src/base.ts
Expand Up @@ -3,4 +3,10 @@ export const assert = (condition: boolean, message: string): asserts condition =
throw new Error(message)
}
export const toString = (v: any) => Object.prototype.toString.call(v)
export const getTypeName = (v: any) => {
if (v === null)
return 'null'
const type = toString(v).slice(8, -1).toLowerCase()
return typeof v === 'object' || typeof v === 'function' ? type : typeof v
}
export const noop = () => {}
27 changes: 27 additions & 0 deletions src/equal.ts
@@ -0,0 +1,27 @@
import { getTypeName } from './base'

export function isDeepEqual(value1: any, value2: any): boolean {
const type1 = getTypeName(value1)
const type2 = getTypeName(value2)
if (type1 !== type2)
return false

if (type1 === 'array') {
if (value1.length !== value2.length)
return false

return value1.every((item: any, i: number) => {
return isDeepEqual(item, value2[i])
})
}
if (type1 === 'object') {
const keyArr = Object.keys(value1)
if (keyArr.length !== Object.keys(value2).length)
return false

return keyArr.every((key: string) => {
return isDeepEqual(value1[key], value2[key])
})
}
return value1 === value2
}

0 comments on commit 1119821

Please sign in to comment.