Last active
January 13, 2021 14:11
-
-
Save mieky/220e47d4ac504ea1f531b6c42b32c3a1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Generate a deterministic pseudo UUID (v4), such that the same input always gives the same output. | |
// Potentially useful for test mocks or such where a specific datum is associated to a specific UUIDs, | |
// but doesn't need guarantees against clashing. | |
// With ES6 modules, you can remove the "require" part, and instead import like this: | |
// import { createHash } from "crypto"; | |
const pseudoUuid = (input) => require("crypto") | |
.createHash("sha256") | |
.update(input) | |
.digest("hex") | |
.replace(/(.{8})(.{4})(.{4})(.{4})(.{12}).*/, "$1-$2-$3-$4-$5"); | |
console.log(pseudoUuid("hello")); // '2cf24dba-5fb0-a30e-26e8-3b2ac5b9e29e' | |
console.log(pseudoUuid("hello")); // '2cf24dba-5fb0-a30e-26e8-3b2ac5b9e29e' | |
console.log(pseudoUuid("bork")); // 'b662ae3a-bc79-8cf6-27f3-1727cf1ea4e0' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment