Created
May 26, 2021 23:22
-
-
Save VitorLuizC/c56b909953b9f001c82367d5f44d2013 to your computer and use it in GitHub Desktop.
React.js useIdentify hook that generates an unique id with really random generated numbers for each name provided.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useMemo } from 'react'; | |
import generateHash from './generateHash.js'; | |
export type Identify = (name: string) => string; | |
function useIdentify(): Identify { | |
const ids = useMemo(() => new Map<string, string>(), []); | |
return useCallback((name) => { | |
if (!ids.has(name)) { | |
ids.set(name, `id-${generateHash()}`); | |
} | |
// `!` was used because it was checked in the `if` above. | |
return ids.get(name)!; | |
}, [ids]); | |
} | |
export default useIdentify; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fromByteToHex from './fromByteToHex'; | |
function generateHash(size = 8): string { | |
const values = new Uint8Array(size / 2); | |
// Fill in values array with really random numbers. | |
window.crypto.getRandomValues(values); | |
return Array.from(values, fromByteToHex).join(''); | |
} | |
export default generateHash; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fromByteToHex(byte: number): string { | |
return byte.toString(16).padStart(2, '0'); | |
} | |
export default fromByteToHex; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment