├── .editorconfig ├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── bench ├── index.js └── package.json ├── bin └── build.js ├── license ├── package.json ├── readme.md ├── src ├── index.d.ts └── index.js └── test ├── collisions.js └── index.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_size = 2 6 | indent_style = tab 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.{json,yml,md}] 13 | indent_style = space 14 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: lukeed 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | name: Node.js v${{ matrix.nodejs }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | nodejs: [8, 10, 12, 14, 16, 18] 12 | steps: 13 | - uses: actions/checkout@v3 14 | - uses: actions/setup-node@v3 15 | with: 16 | node-version: ${{ matrix.nodejs }} 17 | 18 | - name: Install 19 | run: npm install 20 | 21 | - name: Test 22 | if: matrix.nodejs < 18 23 | run: npm test 24 | 25 | - name: Test w/ Coverage 26 | if: matrix.nodejs >= 18 27 | run: | 28 | npm install -g c8 29 | c8 --include=src npm test 30 | 31 | - name: Report 32 | if: matrix.nodejs >= 18 33 | run: | 34 | c8 report --reporter=text-lcov > coverage.lcov 35 | bash <(curl -s https://codecov.io/bash) 36 | env: 37 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | *-lock.* 4 | *.lock 5 | *.log 6 | 7 | /dist 8 | -------------------------------------------------------------------------------- /bench/index.js: -------------------------------------------------------------------------------- 1 | const uuid = require('uuid'); 2 | const assert = require('assert'); 3 | const { Suite } = require('benchmark'); 4 | const nanoid = require('nanoid/non-secure'); 5 | const Hash = require('hashids/cjs'); 6 | const hexoid = require('../dist'); 7 | const uid = require('uid'); 8 | 9 | const size_16 = { 10 | 'hashids/fixed': new Hash('', 16), 11 | 'nanoid/non-secure': nanoid.bind(nanoid, 16), 12 | 'uid': uid.bind(uid, 16), 13 | 'hexoid': hexoid(16), 14 | }; 15 | 16 | const size_25 = { 17 | 'cuid': require('cuid'), 18 | 'hashids/fixed': new Hash('', 25), 19 | 'nanoid/non-secure': nanoid.bind(nanoid, 25), 20 | 'uid': uid.bind(uid, 25), 21 | 'hexoid': hexoid(25), 22 | }; 23 | 24 | const size_36 = { 25 | 'uuid/v1': uuid.v1, 26 | 'uuid/v4': uuid.v4, 27 | '@lukeed/uuid': require('@lukeed/uuid'), 28 | 'hashids/fixed': new Hash('', 36), 29 | 'nanoid/non-secure': nanoid.bind(nanoid, 36), 30 | 'uid': uid.bind(uid, 36), 31 | 'hexoid': hexoid(36), 32 | }; 33 | 34 | function pad(str) { 35 | return str + ' '.repeat(20 - str.length); 36 | } 37 | 38 | function runner(group, size) { 39 | let num = 0; 40 | 41 | console.log(`\nValidation (length = ${size}): `); 42 | Object.keys(group).forEach(name => { 43 | try { 44 | num = 0; 45 | const lib = group[name]; 46 | const isHash = name.startsWith('hashids'); 47 | const output = isHash ? lib.encode(num++) : lib(); 48 | 49 | assert.deepStrictEqual(typeof output, 'string', 'returns string'); 50 | assert.notDeepEqual(output, isHash ? lib.encode(num++) : lib(), 'unqiue strings'); 51 | 52 | console.log(' ✔', pad(name), `(example: "${output}")`); 53 | } catch (err) { 54 | console.log(' ✘', pad(name), `(FAILED @ "${err.message}")`); 55 | } 56 | }); 57 | 58 | console.log(`\nBenchmark (length = ${size}):`); 59 | const bench = new Suite().on('cycle', e => { 60 | console.log(' ' + e.target); 61 | num = 0; // hashids reset 62 | }); 63 | 64 | Object.keys(group).forEach(name => { 65 | if (name.startsWith('hashids')) { 66 | num = 0; 67 | bench.add(pad(name), () => { 68 | group[name].encode(num++); 69 | }); 70 | } else { 71 | bench.add(pad(name), () => { 72 | group[name](); 73 | }); 74 | } 75 | }); 76 | 77 | bench.run(); 78 | } 79 | 80 | // --- 81 | 82 | runner(size_16, 16); 83 | runner(size_25, 25); 84 | runner(size_36, 36); 85 | -------------------------------------------------------------------------------- /bench/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "devDependencies": { 4 | "@lukeed/uuid": "1.0.1", 5 | "benchmark": "2.1.4", 6 | "cuid": "2.1.8", 7 | "uid": "1.0.0", 8 | "hashids": "2.2.1", 9 | "nanoid": "2.1.11", 10 | "uuid": "7.0.1" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /bin/build.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const terser = require('terser'); 5 | const { gzipSync } = require('zlib'); 6 | const pkg = require('../package.json'); 7 | 8 | /** 9 | * @param {string} file 10 | * @param {string} content 11 | */ 12 | function write(file, content) { 13 | let mini = terser.minify(content, { 14 | module: true, 15 | compress: true, 16 | mangle: true, 17 | }); 18 | 19 | let abs = path.join(__dirname, '..', file); 20 | 21 | let dir = path.dirname(abs); 22 | fs.existsSync(dir) || fs.mkdirSync(dir); 23 | fs.writeFileSync(abs, mini.code); 24 | 25 | let num = gzipSync(mini.code).byteLength; 26 | let size = (num < 1024) ? (num + ' B') : `${(num/1024).toFixed(2)} kB`; 27 | 28 | console.log('~> "%s" (%s)', file, size); 29 | } 30 | 31 | /** 32 | * @param {string} input 33 | * @param {Record} outputs 34 | */ 35 | function transform(input, outputs) { 36 | let file = path.resolve(input); 37 | let data = fs.readFileSync(file, 'utf8'); 38 | 39 | // esm -> minify as is 40 | write(outputs.import, data); 41 | 42 | // esm -> cjs -> minify 43 | data = data.replace('export function hexoid', 'exports.hexoid = function'); 44 | write(outputs.require, data); 45 | 46 | if (outputs.types) { 47 | file = file.replace(/\.[mc]?[tj]sx?$/, '.d.ts'); 48 | if (!fs.existsSync(file)) throw new Error(`Missing "${file}" file`); 49 | fs.copyFileSync(file, outputs.types); 50 | console.log('~> "%s"', outputs.types); 51 | } 52 | } 53 | 54 | transform('src/index.js', pkg.exports['.']); 55 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Luke Edwards (lukeed.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hexoid", 3 | "version": "2.0.0", 4 | "repository": "lukeed/hexoid", 5 | "description": "A tiny (190B) and extremely fast utility to generate random IDs of fixed length", 6 | "module": "dist/index.mjs", 7 | "types": "dist/index.d.ts", 8 | "main": "dist/index.js", 9 | "license": "MIT", 10 | "author": { 11 | "name": "Luke Edwards", 12 | "email": "luke.edwards05@gmail.com", 13 | "url": "https://lukeed.com" 14 | }, 15 | "engines": { 16 | "node": ">=8" 17 | }, 18 | "scripts": { 19 | "build": "node bin/build", 20 | "test": "uvu test -r esm -i collisions" 21 | }, 22 | "exports": { 23 | ".": { 24 | "types": "./dist/index.d.ts", 25 | "import": "./dist/index.mjs", 26 | "require": "./dist/index.js" 27 | }, 28 | "./package.json": "./package.json" 29 | }, 30 | "files": [ 31 | "dist" 32 | ], 33 | "keywords": [ 34 | "id", 35 | "uid", 36 | "uuid", 37 | "random", 38 | "generate" 39 | ], 40 | "devDependencies": { 41 | "esm": "3.2.25", 42 | "terser": "4.8.0", 43 | "uvu": "0.5.3" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # hexoid [![CI](https://github.com/lukeed/hexoid/workflows/CI/badge.svg)](https://github.com/lukeed/hexoid/actions) [![licenses](https://licenses.dev/b/npm/hexoid)](https://licenses.dev/npm/hexoid) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/hexoid)](https://codecov.io/gh/lukeed/hexoid) 2 | 3 | > A tiny (190B) and [extremely fast](#benchmarks) utility to generate random IDs of fixed length 4 | 5 | _**Hexadecimal object IDs.** Available for Node.js and the browser._
Generate randomized output strings of fixed length using lowercased hexadecimal pairs. 6 | 7 | > **Notice:** Please note that this is not a cryptographically secure (CSPRNG) generator. 8 | 9 | Additionally, this module is delivered as: 10 | 11 | * **CommonJS**: [`dist/index.js`](https://unpkg.com/hexoid/dist/index.js) 12 | * **ES Module**: [`dist/index.mjs`](https://unpkg.com/hexoid/dist/index.mjs) 13 | 14 | ## Install 15 | 16 | ``` 17 | $ npm install --save hexoid 18 | ``` 19 | 20 | 21 | ## Usage 22 | 23 | ```js 24 | import { hexoid } from 'hexoid'; 25 | 26 | const toID = hexoid(); 27 | // length = 16 (default) 28 | toID(); //=> '52032fedb951da00' 29 | toID(); //=> '52032fedb951da01' 30 | toID(); //=> '52032fedb951da02' 31 | 32 | // customize length 33 | hexoid(25)(); //=> '065359875047c63a037200e00' 34 | hexoid(32)(); //=> 'ca8e4aec7f139d94fcab9cab2eb89f00' 35 | hexoid(48)(); //=> 'c19a4deb5cdeca68534930e67bd0a2f4ed45988724d8d200' 36 | ``` 37 | 38 | 39 | ## API 40 | 41 | ### hexoid(length?) 42 | Returns: `() => string` 43 | 44 | Creates the function that will generate strings. 45 | 46 | #### length 47 | Type: `Number`
48 | Default: `16` 49 | 50 | Then length of the output string. 51 | 52 | > **Important:** Your risk of collisions decreases with longer strings!
Please be aware of the [Birthday Problem](https://betterexplained.com/articles/understanding-the-birthday-paradox/)! You may need more combinations than you'd expect. 53 | 54 | The **maximum combinations** are known given the following formula: 55 | 56 | ```js 57 | const combos = 256 ** (len/2); 58 | ``` 59 | 60 | 61 | ## Benchmarks 62 | 63 | > Running on Node.js v10.13.0 64 | 65 | ``` 66 | Validation (length = 16): 67 | ✔ hashids/fixed (example: "LkQWjnegYbwZ1p0G") 68 | ✔ nanoid/non-secure (example: "sLlVL5X3M5k2fo58") 69 | ✔ uid (example: "3d0ckwcnjiuu91hj") 70 | ✔ hexoid (example: "de96b62e663ef300") 71 | Benchmark (length = 16): 72 | hashids/fixed x 349,462 ops/sec ±0.28% (93 runs sampled) 73 | nanoid/non-secure x 3,337,573 ops/sec ±0.28% (96 runs sampled) 74 | uid x 3,553,482 ops/sec ±0.51% (90 runs sampled) 75 | hexoid x 81,081,364 ops/sec ±0.18% (96 runs sampled) 76 | 77 | 78 | Validation (length = 25): 79 | ✔ cuid (example: "ck7lj5hbf00000v7c9gox6yfh") 80 | ✔ hashids/fixed (example: "r9JOyLkQWjnegYbwZ1p0GDXNm") 81 | ✔ nanoid/non-secure (example: "hI202PVPJQRNrP6o6z4pXz4m0") 82 | ✔ uid (example: "9904e9w130buxaw7n8358mn2f") 83 | ✔ hexoid (example: "01dfab2c14e37768eb7605a00") 84 | Benchmark (length = 25): 85 | cuid x 161,636 ops/sec ±1.36% (89 runs sampled) 86 | hashids/fixed x 335,439 ops/sec ±2.40% (94 runs sampled) 87 | nanoid/non-secure x 2,254,073 ops/sec ±0.23% (96 runs sampled) 88 | uid x 2,483,275 ops/sec ±0.38% (95 runs sampled) 89 | hexoid x 75,715,843 ops/sec ±0.27% (95 runs sampled) 90 | 91 | 92 | Validation (length = 36): 93 | ✔ uuid/v1 (example: "c3dc1ed0-629a-11ea-8bfb-8ffc49585f54") 94 | ✔ uuid/v4 (example: "8c89f0ca-f01e-4c84-bd71-e645bab84552") 95 | ✔ hashids/fixed (example: "EVq3Pr9JOyLkQWjnegYbwZ1p0GDXNmRBlAxg") 96 | ✔ @lukeed/uuid (example: "069ad676-48f9-4452-b11d-f20c3872dc1f") 97 | ✔ nanoid/non-secure (example: "jAZjrcDmHH6P1rT9EFdCdHUpF440SjAKwb2A") 98 | ✔ uid (example: "5mhi30lgy5d0glmuy81llelbzdko518ow1sx") 99 | ✔ hexoid (example: "615209331f0b4630acf69999ccfc95a23200") 100 | Benchmark (length = 36): 101 | uuid/v1 x 1,487,947 ops/sec ±0.18% (98 runs sampled) 102 | uuid/v4 x 334,868 ops/sec ±1.08% (90 runs sampled) 103 | @lukeed/uuid x 6,352,445 ops/sec ±0.27% (91 runs sampled) 104 | hashids/fixed x 322,914 ops/sec ±0.27% (93 runs sampled) 105 | nanoid/non-secure x 1,592,708 ops/sec ±0.25% (91 runs sampled) 106 | uid x 1,789,492 ops/sec ±0.29% (92 runs sampled) 107 | hexoid x 71,746,692 ops/sec ±0.29% (93 runs sampled) 108 | ``` 109 | 110 | ## Related 111 | 112 | - [uid](https://github.com/lukeed/uid) - A smaller (134B) but slower variant of this module with a different API 113 | - [@lukeed/uuid](https://github.com/lukeed/uuid) - A tiny (230B), fast, and cryptographically secure UUID (V4) generator for Node and the browser 114 | 115 | 116 | ## License 117 | 118 | MIT © [Luke Edwards](https://lukeed.com) 119 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | export function hexoid(len?: number): () => string; 2 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | var IDX=256, HEX=[]; 2 | while (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1); 3 | 4 | export function hexoid(len) { 5 | len = len || 16; 6 | var str='', num=0; 7 | return function () { 8 | if (!str || num === 256) { 9 | str=''; num=(1+len)/2 | 0; 10 | while (num--) str += HEX[256 * Math.random() | 0]; 11 | str = str.substring(num=0, len-2); 12 | } 13 | return str + HEX[num++]; 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /test/collisions.js: -------------------------------------------------------------------------------- 1 | // $ node test/collisions 16 1e7 2 | const [len=8, cycles] = process.argv.slice(2); 3 | const { hexoid } = require('../dist'); 4 | 5 | const toUID = hexoid(+len); 6 | const total = cycles ? +cycles : 1e6; 7 | 8 | console.log('~> item total:', total.toLocaleString()); 9 | console.log('~> hash length:', +len); 10 | 11 | let sentry = new Set(); 12 | let i=0, tmp, duplicates=0; 13 | for (; i < total; i++) { 14 | tmp = toUID(); 15 | if (sentry.has(tmp)) { 16 | duplicates++; 17 | } else { 18 | sentry.add(tmp); 19 | } 20 | } 21 | 22 | console.log('iterations:', total.toLocaleString()); 23 | console.log('collisions:', duplicates.toLocaleString()); 24 | console.log('percentage:', (duplicates / total * 100).toFixed(4) + '%'); 25 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | import { test } from 'uvu'; 2 | import * as assert from 'uvu/assert'; 3 | import { hexoid } from '../src/index.js'; 4 | 5 | test('exports', () => { 6 | assert.type(hexoid, 'function', 'exports function'); 7 | }); 8 | 9 | 10 | test('returns', () => { 11 | let output = hexoid(); 12 | assert.type(output, 'function', 'returns a function'); 13 | assert.type(output(), 'string', '~> returns a string'); 14 | assert.is(output().length, 16, '~> has 16 characters (default)'); 15 | }); 16 | 17 | 18 | test('length :: 8', () => { 19 | let i=0, tmp; 20 | let gen = hexoid(8); 21 | for (; i < 1e3; i++) { 22 | tmp = gen(); 23 | assert.is(tmp.length, 8, `"${tmp}" is not 8 characters!`); 24 | } 25 | }); 26 | 27 | 28 | test('length :: 11', () => { 29 | let i=0, tmp; 30 | let gen = hexoid(11); 31 | for (; i < 1e3; i++) { 32 | tmp = gen(); 33 | assert.is(tmp.length, 11, `"${tmp}" is not 11 characters!`); 34 | } 35 | }); 36 | 37 | 38 | test('length :: 25', () => { 39 | let i=0, tmp; 40 | let gen = hexoid(25); 41 | for (; i < 1e3; i++) { 42 | tmp = gen(); 43 | assert.is(tmp.length, 25, `"${tmp}" is not 25 characters!`); 44 | } 45 | }); 46 | 47 | 48 | test('length :: 48', () => { 49 | let i=0, tmp; 50 | let gen = hexoid(48); 51 | for (; i < 1e3; i++) { 52 | tmp = gen(); 53 | assert.is(tmp.length, 48, `"${tmp}" is not 48 characters!`); 54 | } 55 | }); 56 | 57 | 58 | test('unique', () => { 59 | let gen = hexoid(); 60 | assert.is.not(gen(), gen(), '~> single'); 61 | 62 | let items = new Set(); 63 | for (let i=5e6; i--;) items.add(gen()); 64 | assert.is(items.size, 5e6, '~> 5,000,000 uniques'); 65 | }); 66 | 67 | 68 | test.run(); 69 | --------------------------------------------------------------------------------