Add nanoid/async
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andrey Sitnik · committed by Andrey Sitnik · parent e31f74d · Browse files · 7 files·+203 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+203 added−1 removed
- tests:+125 added−0 removed
- other:+78 added−1 removed
Provenance
- Commit
2d39104- Tree
5f859aa- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
Andrey Sitnik <andrey@sitnik.ru>- Parent
e31f74d
7 files changed+203 added−1 removed
added:test/async.test.js+81 added
1+var crypto = require('crypto')2+3+var async = require('../async')4+var url = require('../url')5+6+function times (size, callback) {7+ var array = []8+ for (var i = 0; i < 100; i++) {9+ array.push(1)10+ }11+ return array.map(callback)12+}13+14+var originRandom = crypto.randomBytes15+afterEach(function () {16+ crypto.randomBytes = originRandom17+})18+19+it('generates URL-friendly IDs', function () {20+ return Promise.all(times(100, function () {21+ return async().then(function (id) {22+ expect(id).toHaveLength(21)23+ expect(typeof id).toEqual('string')24+ for (var j = 0; j < id.length; j++) {25+ expect(url).toContain(id[j])26+ }27+ })28+ }))29+})30+31+it('changes ID length', function () {32+ return async(10).then(function (id) {33+ expect(id).toHaveLength(10)34+ })35+})36+37+it('has no collisions', function () {38+ return Promise.all(times(100 * 1000, function () {39+ return async()40+ })).then(function (ids) {41+ ids.reduce(function (used, id) {42+ expect(used[id]).not.toBeDefined()43+ used[id] = true44+ return used45+ }, [])46+ })47+})48+49+it('has flat distribution', function () {50+ var COUNT = 100 * 100051+ var LENGTH = async().length52+53+ var chars = { }54+ return Promise.all(times(COUNT, function () {55+ var id = async()56+ for (var j = 0; j < id.length; j++) {57+ var char = id[j]58+ if (!chars[char]) chars[char] = 059+ chars[char] += 160+ }61+ })).then(function () {62+ var max = 063+ var min = Number.MAX_SAFE_INTEGER64+ for (var k in chars) {65+ var distribution = (chars[k] * url.length) / (COUNT * LENGTH)66+ if (distribution > max) max = distribution67+ if (distribution < min) min = distribution68+ }69+ expect(max - min).toBeLessThanOrEqual(0.05)70+ })71+})72+73+it('rejects Promise on error', function () {74+ var error = new Error('test')75+ crypto.randomBytes = function (size, callback) {76+ callback(error)77+ }78+ return async().catch(function (e) {79+ expect(e).toBe(error)80+ })81+})modified:test/benchmark+17 added
7 unmodified lines8 9 var nonSecure = require('../non-secure')10 var generate = require('../generate')11 var nanoid = require('../')12+var async = require('../async')13 14 var suite = new benchmark.Suite()15 16 function formatNumber (number) {17 unmodified lines34 })35 .add('shortid', function () {36 shortid()37 })38+ .add('uid', {39+ defer: true,40+ fn: function (defer) {41+ uid(21).then(function () {42+ defer.resolve()43+ })44+ }45+ })46+ .add('nanoid/async', {47+ defer: true,48+ fn: function (defer) {49+ async().then(function () {50+ defer.resolve()51+ })52+ }53+ })54 .add('rndm', function () {55 rndm(21)56 })57 .add('nanoid/non-secure', function () {8 unmodified linesmodified:test/browser.test.js+27 added
8 unmodified lines91011121314151617181920212223242526276 unmodified lines343536373839404142434445464748495051525354558 unmodified lines }}
var nanoid = require('../index.browser')var async = require('../async.browser')var url = require('../url')
function times (size, callback) { var array = [] for (var i = 0; i < 100; i++) { array.push(1) } return array.map(callback)}
it('generates URL-friendly IDs', function () { for (var i = 0; i < 100; i++) { var id = nanoid() expect(id).toHaveLength(21)6 unmodified lines
it('changes ID length', function () { expect(nanoid(10)).toHaveLength(10)})
it('generates IDs with Promise', function () { return Promise.all(times(100, function () { return async().then(function (id) { expect(id).toHaveLength(21) expect(typeof id).toEqual('string') for (var i = 0; i < id.length; i++) { expect(url).toContain(id[i]) } }) }))})
it('changes ID length in async', function () { return async(10).then(function (id) { expect(id).toHaveLength(10) })})added:async.browser.js+13 added
12345678910111213var crypto = self.crypto || self.msCrypto
var url = '_~getRandomVcryp0123456789bfhijklqsuvwxzABCDEFGHIJKLMNOPQSTUWXYZ'
module.exports = function (size) { size = size || 21 var id = '' var bytes = crypto.getRandomValues(new Uint8Array(size)) while (0 < size--) { id += url[bytes[size] & 63] } return Promise.resolve(id)}added:async.js+39 added
123456789101112131415161718192021222324252627282930313233343536373839var crypto = require('crypto')
var url = require('./url')
/** * Generate secure URL-friendly unique ID. Non-blocking version. * * By default, ID will have 21 symbols to have a collision probability similar * to UUID v4. * * @param {number} [size=21] The number of symbols in ID. * * @return {Promise} Promise with random string. * * @example * var nanoidAsync = require('nanoid/async') * nanoidAsync.then(function (id) { * model.id = id * }) * * @name async * @function */module.exports = function (size) { size = size || 21 return new Promise(function (resolve, reject) { crypto.randomBytes(size, function (err, bytes) { if (err) { reject(err) } else { var id = '' while (0 < size--) { id += url[bytes[size] & 63] } resolve(id) } }) })}modified:package.json+6 added-1 removed
11 unmodified lines12 "license": "MIT",13 "repository": "ai/nanoid",14 "browser": {15 "./random.js": "./random.browser.js",16- "./index.js": "./index.browser.js"16+ "./index.js": "./index.browser.js",17+ "./async.js": "./async.browser.js"18 },19 "devDependencies": {20 "benchmark": "^2.1.4",21 "chalk": "^2.4.1",46 unmodified lines68 },69 {70 "path": "non-secure.js",71 "limit": "118 B"72+ },73+ {74+ "path": "async.js",75+ "limit": "157 B"76 }77 ],78 "eslintConfig": {79 "extends": "eslint-config-logux/browser",54 unmodified linesmodified:README.md+20 added
83 unmodified lines84 nanoid/generate 352,418 ops/sec85 uid.sync 332,502 ops/sec86 uuid/v4 345,867 ops/sec87 shortid 34,193 ops/sec88+uid 78,343 ops/sec89+nanoid/async 79,173 ops/sec90 rndm 2,557,778 ops/sec91 nanoid/non-secure 2,578,934 ops/sec92 ```93 41 unmodified lines135 model.id = nanoid() //=> "Uakgb_J5m9g~0JDMbcJqLJ"136 ```137 138 139+## Async140+141+To generate hardware random bytes, CPU will collect electromagnetic noise.142+During the collection, CPU doesn’t work. So if we will use asynchronous API143+for hardware random generator, your other code could be executed durring144+the entropy collection.145+146+```js147+var nanoid = require('nanoid/async')148+nanoid.then(function (id) {149+ model.id = id150+})151+```152+153+Unfortunately, you will not have any benefits in browser, since Web Crypto API154+doesn’t have asynchronous API.155+156+157 ### Custom Alphabet or Length158 159 If you want to change the ID's alphabet or length160 you can use the low-level `generate` module.78 unmodified lines