Skip to content

Instantly share code, notes, and snippets.

@programus
Last active May 15, 2025 09:10
Show Gist options
  • Save programus/0d88361fc7be92e860368e8bf904ac2d to your computer and use it in GitHub Desktop.
Save programus/0d88361fc7be92e860368e8bf904ac2d to your computer and use it in GitHub Desktop.
TypeScript function to identify references of everything
// check whether the object is the same reference
// from https://stackoverflow.com/a/43963612/1166461
export const id = (() => {
const useless = typeof (1 as any)
let currentId = 0
const map = new WeakMap()
type ResultType = number|bigint|string|boolean|undefined
const objId = <T extends object>(obj: T): ResultType => {
const o = obj as object
if (!map.has(o)) {
map.set(o, ++currentId)
}
return map.get(o)
}
const primitiveId = (obj: number|bigint|string|boolean|undefined): ResultType => obj
const objectMap = {
'object': true,
'function': true,
'symbol': true,
}
return <T extends object>(obj: Parameters<typeof primitiveId>[0] | T): ResultType => {
const objType = typeof obj
return objType in objectMap ? objId(obj as unknown as object) : primitiveId(obj as Parameters<typeof primitiveId>[0])
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment