Skip to content

Instantly share code, notes, and snippets.

@mieky
Last active January 13, 2021 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mieky/220e47d4ac504ea1f531b6c42b32c3a1 to your computer and use it in GitHub Desktop.
Save mieky/220e47d4ac504ea1f531b6c42b32c3a1 to your computer and use it in GitHub Desktop.
// 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