Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(array): isDeepEqual and uniqueBy #24

Merged
merged 6 commits into from
Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}