pax_global_header00006660000000000000000000000064147024337040014516gustar00rootroot0000000000000052 comment=a23cb66b42595b3c6c443ca2bbea9aac50504cc9 lukeed-hexoid-b04bfd6/000077500000000000000000000000001470243370400147365ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/.editorconfig000066400000000000000000000003231470243370400174110ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_size = 2 indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.{json,yml,md}] indent_style = space lukeed-hexoid-b04bfd6/.github/000077500000000000000000000000001470243370400162765ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/.github/FUNDING.yml000066400000000000000000000000171470243370400201110ustar00rootroot00000000000000github: lukeed lukeed-hexoid-b04bfd6/.github/workflows/000077500000000000000000000000001470243370400203335ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/.github/workflows/ci.yml000066400000000000000000000014261470243370400214540ustar00rootroot00000000000000name: CI on: [push, pull_request] jobs: test: name: Node.js v${{ matrix.nodejs }} runs-on: ubuntu-latest strategy: matrix: nodejs: [8, 10, 12, 14, 16, 18] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: ${{ matrix.nodejs }} - name: Install run: npm install - name: Test if: matrix.nodejs < 18 run: npm test - name: Test w/ Coverage if: matrix.nodejs >= 18 run: | npm install -g c8 c8 --include=src npm test - name: Report if: matrix.nodejs >= 18 run: | c8 report --reporter=text-lcov > coverage.lcov bash <(curl -s https://codecov.io/bash) env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} lukeed-hexoid-b04bfd6/.gitignore000066400000000000000000000000641470243370400167260ustar00rootroot00000000000000.DS_Store node_modules *-lock.* *.lock *.log /dist lukeed-hexoid-b04bfd6/bench/000077500000000000000000000000001470243370400160155ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/bench/index.js000066400000000000000000000036651470243370400174740ustar00rootroot00000000000000const uuid = require('uuid'); const assert = require('assert'); const { Suite } = require('benchmark'); const nanoid = require('nanoid/non-secure'); const Hash = require('hashids/cjs'); const hexoid = require('../dist'); const uid = require('uid'); const size_16 = { 'hashids/fixed': new Hash('', 16), 'nanoid/non-secure': nanoid.bind(nanoid, 16), 'uid': uid.bind(uid, 16), 'hexoid': hexoid(16), }; const size_25 = { 'cuid': require('cuid'), 'hashids/fixed': new Hash('', 25), 'nanoid/non-secure': nanoid.bind(nanoid, 25), 'uid': uid.bind(uid, 25), 'hexoid': hexoid(25), }; const size_36 = { 'uuid/v1': uuid.v1, 'uuid/v4': uuid.v4, '@lukeed/uuid': require('@lukeed/uuid'), 'hashids/fixed': new Hash('', 36), 'nanoid/non-secure': nanoid.bind(nanoid, 36), 'uid': uid.bind(uid, 36), 'hexoid': hexoid(36), }; function pad(str) { return str + ' '.repeat(20 - str.length); } function runner(group, size) { let num = 0; console.log(`\nValidation (length = ${size}): `); Object.keys(group).forEach(name => { try { num = 0; const lib = group[name]; const isHash = name.startsWith('hashids'); const output = isHash ? lib.encode(num++) : lib(); assert.deepStrictEqual(typeof output, 'string', 'returns string'); assert.notDeepEqual(output, isHash ? lib.encode(num++) : lib(), 'unqiue strings'); console.log(' ✔', pad(name), `(example: "${output}")`); } catch (err) { console.log(' ✘', pad(name), `(FAILED @ "${err.message}")`); } }); console.log(`\nBenchmark (length = ${size}):`); const bench = new Suite().on('cycle', e => { console.log(' ' + e.target); num = 0; // hashids reset }); Object.keys(group).forEach(name => { if (name.startsWith('hashids')) { num = 0; bench.add(pad(name), () => { group[name].encode(num++); }); } else { bench.add(pad(name), () => { group[name](); }); } }); bench.run(); } // --- runner(size_16, 16); runner(size_25, 25); runner(size_36, 36); lukeed-hexoid-b04bfd6/bench/package.json000066400000000000000000000003261470243370400203040ustar00rootroot00000000000000{ "private": true, "devDependencies": { "@lukeed/uuid": "1.0.1", "benchmark": "2.1.4", "cuid": "2.1.8", "uid": "1.0.0", "hashids": "2.2.1", "nanoid": "2.1.11", "uuid": "7.0.1" } } lukeed-hexoid-b04bfd6/bin/000077500000000000000000000000001470243370400155065ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/bin/build.js000066400000000000000000000024711470243370400171470ustar00rootroot00000000000000// @ts-check const fs = require('fs'); const path = require('path'); const terser = require('terser'); const { gzipSync } = require('zlib'); const pkg = require('../package.json'); /** * @param {string} file * @param {string} content */ function write(file, content) { let mini = terser.minify(content, { module: true, compress: true, mangle: true, }); let abs = path.join(__dirname, '..', file); let dir = path.dirname(abs); fs.existsSync(dir) || fs.mkdirSync(dir); fs.writeFileSync(abs, mini.code); let num = gzipSync(mini.code).byteLength; let size = (num < 1024) ? (num + ' B') : `${(num/1024).toFixed(2)} kB`; console.log('~> "%s" (%s)', file, size); } /** * @param {string} input * @param {Record} outputs */ function transform(input, outputs) { let file = path.resolve(input); let data = fs.readFileSync(file, 'utf8'); // esm -> minify as is write(outputs.import, data); // esm -> cjs -> minify data = data.replace('export function hexoid', 'exports.hexoid = function'); write(outputs.require, data); if (outputs.types) { file = file.replace(/\.[mc]?[tj]sx?$/, '.d.ts'); if (!fs.existsSync(file)) throw new Error(`Missing "${file}" file`); fs.copyFileSync(file, outputs.types); console.log('~> "%s"', outputs.types); } } transform('src/index.js', pkg.exports['.']); lukeed-hexoid-b04bfd6/license000066400000000000000000000021201470243370400162760ustar00rootroot00000000000000MIT License Copyright (c) Luke Edwards (lukeed.com) 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. lukeed-hexoid-b04bfd6/package.json000066400000000000000000000016351470243370400172310ustar00rootroot00000000000000{ "name": "hexoid", "version": "2.0.0", "repository": "lukeed/hexoid", "description": "A tiny (190B) and extremely fast utility to generate random IDs of fixed length", "module": "dist/index.mjs", "types": "dist/index.d.ts", "main": "dist/index.js", "license": "MIT", "author": { "name": "Luke Edwards", "email": "luke.edwards05@gmail.com", "url": "https://lukeed.com" }, "engines": { "node": ">=8" }, "scripts": { "build": "node bin/build", "test": "uvu test -r esm -i collisions" }, "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.js" }, "./package.json": "./package.json" }, "files": [ "dist" ], "keywords": [ "id", "uid", "uuid", "random", "generate" ], "devDependencies": { "esm": "3.2.25", "terser": "4.8.0", "uvu": "0.5.3" } } lukeed-hexoid-b04bfd6/readme.md000066400000000000000000000107711470243370400165230ustar00rootroot00000000000000# 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) > A tiny (190B) and [extremely fast](#benchmarks) utility to generate random IDs of fixed length _**Hexadecimal object IDs.** Available for Node.js and the browser._
Generate randomized output strings of fixed length using lowercased hexadecimal pairs. > **Notice:** Please note that this is not a cryptographically secure (CSPRNG) generator. Additionally, this module is delivered as: * **CommonJS**: [`dist/index.js`](https://unpkg.com/hexoid/dist/index.js) * **ES Module**: [`dist/index.mjs`](https://unpkg.com/hexoid/dist/index.mjs) ## Install ``` $ npm install --save hexoid ``` ## Usage ```js import { hexoid } from 'hexoid'; const toID = hexoid(); // length = 16 (default) toID(); //=> '52032fedb951da00' toID(); //=> '52032fedb951da01' toID(); //=> '52032fedb951da02' // customize length hexoid(25)(); //=> '065359875047c63a037200e00' hexoid(32)(); //=> 'ca8e4aec7f139d94fcab9cab2eb89f00' hexoid(48)(); //=> 'c19a4deb5cdeca68534930e67bd0a2f4ed45988724d8d200' ``` ## API ### hexoid(length?) Returns: `() => string` Creates the function that will generate strings. #### length Type: `Number`
Default: `16` Then length of the output string. > **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. The **maximum combinations** are known given the following formula: ```js const combos = 256 ** (len/2); ``` ## Benchmarks > Running on Node.js v10.13.0 ``` Validation (length = 16): ✔ hashids/fixed (example: "LkQWjnegYbwZ1p0G") ✔ nanoid/non-secure (example: "sLlVL5X3M5k2fo58") ✔ uid (example: "3d0ckwcnjiuu91hj") ✔ hexoid (example: "de96b62e663ef300") Benchmark (length = 16): hashids/fixed x 349,462 ops/sec ±0.28% (93 runs sampled) nanoid/non-secure x 3,337,573 ops/sec ±0.28% (96 runs sampled) uid x 3,553,482 ops/sec ±0.51% (90 runs sampled) hexoid x 81,081,364 ops/sec ±0.18% (96 runs sampled) Validation (length = 25): ✔ cuid (example: "ck7lj5hbf00000v7c9gox6yfh") ✔ hashids/fixed (example: "r9JOyLkQWjnegYbwZ1p0GDXNm") ✔ nanoid/non-secure (example: "hI202PVPJQRNrP6o6z4pXz4m0") ✔ uid (example: "9904e9w130buxaw7n8358mn2f") ✔ hexoid (example: "01dfab2c14e37768eb7605a00") Benchmark (length = 25): cuid x 161,636 ops/sec ±1.36% (89 runs sampled) hashids/fixed x 335,439 ops/sec ±2.40% (94 runs sampled) nanoid/non-secure x 2,254,073 ops/sec ±0.23% (96 runs sampled) uid x 2,483,275 ops/sec ±0.38% (95 runs sampled) hexoid x 75,715,843 ops/sec ±0.27% (95 runs sampled) Validation (length = 36): ✔ uuid/v1 (example: "c3dc1ed0-629a-11ea-8bfb-8ffc49585f54") ✔ uuid/v4 (example: "8c89f0ca-f01e-4c84-bd71-e645bab84552") ✔ hashids/fixed (example: "EVq3Pr9JOyLkQWjnegYbwZ1p0GDXNmRBlAxg") ✔ @lukeed/uuid (example: "069ad676-48f9-4452-b11d-f20c3872dc1f") ✔ nanoid/non-secure (example: "jAZjrcDmHH6P1rT9EFdCdHUpF440SjAKwb2A") ✔ uid (example: "5mhi30lgy5d0glmuy81llelbzdko518ow1sx") ✔ hexoid (example: "615209331f0b4630acf69999ccfc95a23200") Benchmark (length = 36): uuid/v1 x 1,487,947 ops/sec ±0.18% (98 runs sampled) uuid/v4 x 334,868 ops/sec ±1.08% (90 runs sampled) @lukeed/uuid x 6,352,445 ops/sec ±0.27% (91 runs sampled) hashids/fixed x 322,914 ops/sec ±0.27% (93 runs sampled) nanoid/non-secure x 1,592,708 ops/sec ±0.25% (91 runs sampled) uid x 1,789,492 ops/sec ±0.29% (92 runs sampled) hexoid x 71,746,692 ops/sec ±0.29% (93 runs sampled) ``` ## Related - [uid](https://github.com/lukeed/uid) - A smaller (134B) but slower variant of this module with a different API - [@lukeed/uuid](https://github.com/lukeed/uuid) - A tiny (230B), fast, and cryptographically secure UUID (V4) generator for Node and the browser ## License MIT © [Luke Edwards](https://lukeed.com) lukeed-hexoid-b04bfd6/src/000077500000000000000000000000001470243370400155255ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/src/index.d.ts000066400000000000000000000000641470243370400174260ustar00rootroot00000000000000export function hexoid(len?: number): () => string; lukeed-hexoid-b04bfd6/src/index.js000066400000000000000000000005541470243370400171760ustar00rootroot00000000000000var IDX=256, HEX=[]; while (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1); export function hexoid(len) { len = len || 16; var str='', num=0; return function () { if (!str || num === 256) { str=''; num=(1+len)/2 | 0; while (num--) str += HEX[256 * Math.random() | 0]; str = str.substring(num=0, len-2); } return str + HEX[num++]; }; } lukeed-hexoid-b04bfd6/test/000077500000000000000000000000001470243370400157155ustar00rootroot00000000000000lukeed-hexoid-b04bfd6/test/collisions.js000066400000000000000000000011671470243370400204360ustar00rootroot00000000000000// $ node test/collisions 16 1e7 const [len=8, cycles] = process.argv.slice(2); const { hexoid } = require('../dist'); const toUID = hexoid(+len); const total = cycles ? +cycles : 1e6; console.log('~> item total:', total.toLocaleString()); console.log('~> hash length:', +len); let sentry = new Set(); let i=0, tmp, duplicates=0; for (; i < total; i++) { tmp = toUID(); if (sentry.has(tmp)) { duplicates++; } else { sentry.add(tmp); } } console.log('iterations:', total.toLocaleString()); console.log('collisions:', duplicates.toLocaleString()); console.log('percentage:', (duplicates / total * 100).toFixed(4) + '%'); lukeed-hexoid-b04bfd6/test/index.js000066400000000000000000000025171470243370400173670ustar00rootroot00000000000000import { test } from 'uvu'; import * as assert from 'uvu/assert'; import { hexoid } from '../src/index.js'; test('exports', () => { assert.type(hexoid, 'function', 'exports function'); }); test('returns', () => { let output = hexoid(); assert.type(output, 'function', 'returns a function'); assert.type(output(), 'string', '~> returns a string'); assert.is(output().length, 16, '~> has 16 characters (default)'); }); test('length :: 8', () => { let i=0, tmp; let gen = hexoid(8); for (; i < 1e3; i++) { tmp = gen(); assert.is(tmp.length, 8, `"${tmp}" is not 8 characters!`); } }); test('length :: 11', () => { let i=0, tmp; let gen = hexoid(11); for (; i < 1e3; i++) { tmp = gen(); assert.is(tmp.length, 11, `"${tmp}" is not 11 characters!`); } }); test('length :: 25', () => { let i=0, tmp; let gen = hexoid(25); for (; i < 1e3; i++) { tmp = gen(); assert.is(tmp.length, 25, `"${tmp}" is not 25 characters!`); } }); test('length :: 48', () => { let i=0, tmp; let gen = hexoid(48); for (; i < 1e3; i++) { tmp = gen(); assert.is(tmp.length, 48, `"${tmp}" is not 48 characters!`); } }); test('unique', () => { let gen = hexoid(); assert.is.not(gen(), gen(), '~> single'); let items = new Set(); for (let i=5e6; i--;) items.add(gen()); assert.is(items.size, 5e6, '~> 5,000,000 uniques'); }); test.run();