Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
}