Last active
October 15, 2021 21:10
-
-
Save tmarshall/93f56d2ced4176abf784e3f8a97d64b8 to your computer and use it in GitHub Desktop.
stateful string hash code hook
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 { useEffect, useState } from 'react' | |
/* | |
takes in a string and returns a hash int code | |
which can be useful for generating react keys | |
base on input strings, that may or may not change | |
const [hashCode, setHashCodeString] = useHashCode() | |
*/ | |
function useHashCode(initialString = '') { | |
const [str, setStr] = useState(initialString) | |
const [hash, setHash] = useState(0) | |
useEffect(() => { | |
let newHash = 0 | |
if (str.length === 0) { | |
return newHash | |
} | |
for (let i = 0; i < str.length; i++) { | |
const chr = str.charCodeAt(i) | |
newHash = ((newHash << 5) - newHash) + chr | |
newHash |= 0 // convert to 32bit int | |
} | |
setHash(newHash) | |
}, [str, setHash]) | |
return [hash, setStr] | |
} | |
export default useHashCode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment