Skip to content

Instantly share code, notes, and snippets.

@gutchom
Created January 22, 2020 01:58
Show Gist options
  • Save gutchom/f9f941508d087e976027b14a5d449c09 to your computer and use it in GitHub Desktop.
Save gutchom/f9f941508d087e976027b14a5d449c09 to your computer and use it in GitHub Desktop.
Help me about TypeScript
export default function equal<T>(a: T, b: T): boolean {
return typeof a === 'object' ? Object.keys(a).every(<K extends keyof T>(key: K) => equal(a[key], b[key])) : a === b
}
export function refer<T, K extends keyof T>(variable: T, property: K): T[K] {
return variable[property]
}
Array.prototype.dedupe = function dedupe<T>(comparison?: ((val1: T, val2: T) => boolean)|string, ...key: string[]): T[] {
if (typeof comparison === 'string') {
key.unshift(comparison)
}
return (this as T[]).filter(
(val1, index, self) => typeof comparison === 'function'
? -1 > self.findIndex(val2 => comparison(val1, val2))
: typeof comparison === 'string'
? index <= self.findIndex(val2 => key.reduce(refer, val1) === key.reduce(refer, val2))
: index <= self.findIndex(val2 => equal(val1, val2))
)
}
Array.prototype.sortByKey = function sortByKey<T>(...key: string[]): T[] {
if (typeof this[0] !== 'object') {
throw new TypeError('This array have to made of object.')
}
return this.sort((a: T, b: T) => (a = key.reduce(refer, a) as any) < (b = key.reduce(refer, b) as any) ? -1 : a > b ? 1 : 0)
}
@smellman
Copy link

export default function equal<T>(a: T, b: T): boolean {
  return typeof a === 'object' ? (Object.keys(a) as (keyof T)[]).every(<K extends keyof T>(key: K) => equal(a[key], b[key])) : a === b
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment