Skip to content

Instantly share code, notes, and snippets.

@ericyd
Created March 6, 2020 18:02
Show Gist options
  • Save ericyd/103bca607c9da8f80e1f2f8db230d22e to your computer and use it in GitHub Desktop.
Save ericyd/103bca607c9da8f80e1f2f8db230d22e to your computer and use it in GitHub Desktop.
Poor man's UUID
/**
* This is NOT a cryptographically strong UUID algorithm
* It is purely for quick-n-easy drag-n-drop scripting applications where
* data quality does not matter.
*
* For a proper UUID implementation, see
* https://github.com/uuidjs/uuid/blob/master/src/v4.js
*/
const max = Math.pow(2, 8) - 1
// this slick trick thanks to https://github.com/uuidjs/uuid/blob/e8cb0a03a5408415d1f93a1499d8cda47246adc7/src/bytesToUuid.js#L7
// this avoids having to manually add a `0` to hex values with only 1 char
const toHex = n => (n + 0x100).toString(16).substr(1)
const adjust = (n, min, max) => Math.round(n * (max - min) + min)
const rand8bit = () => adjust(Math.random(), 0, max)
const rand8bitHex = () => toHex(rand8bit())
const repeatHex = n => Array(n).fill(0).map(() => rand8bitHex()).join('')
const uuid = () => [repeatHex(4), repeatHex(2), repeatHex(2), repeatHex(2), repeatHex(6)].join('-')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment