Skip to content
Myr

Fix non-integer size in customRandom() (#616)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by lostsignals · committed by GitHub · parent ccb0e6e · Browse files · 4 files+17 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: L0stS1gnals <nhm7226@g.rit.edu>

Diff stats

4 files+17 added−3 removed

  • tests:+12 added−0 removed
  • other:+5 added−3 removed

4 files+17 added−3 removed

modified:test/index.test.js+12 added
235 unmodified lines
236 let third = nanoid2()237 notEqual(second, third)238 })239240 test(`supports non-integer size`, () => {241 let nanoid2 = customAlphabet('0123456789abcdef')242 let ids = new Set()243 for (let i = 0; i < 10; i++) {244 let id = nanoid2(16.5)245 equal(id.length, 16)246 ids.add(id)247 }248 equal(ids.size, 10)249 })250251 test(`supports multi-byte characters`, () => {252 let ALPHABET = 'абвгд'253 let nanoid2 = customAlphabet(ALPHABET, 10)254 for (let i = 0; i < 100; i++) {
65 unmodified lines
320 }321 let nanoid4 = customRandom('abcd', 4, fakeRandom)322 equal(nanoid4(), 'dddc')323 equal(nanoid4(0), '')324 equal(nanoid4(4.5), 'dddc')325 })326 })327328 describe('urlAlphabet', () => {
43 unmodified lines
modified:index.browser.js+2 added-1 removed
modified:index.js+2 added-1 removed
47 unmodified lines
48 let id = ''49 while (true) {50 let bytes = getRandom(size)51 // A compact alternative for `for (let i = 0; i < step; i++)`.52 let i = size52 // `|=` convert `size` to integer, so it can be used as a byte index53 let i = (size |= 0)54 while (i--) {55 // Here, `& mask` is equivalent to `% alphabet.length`, but faster56 id += alphabet[bytes[i] & mask]57 if (id.length >= size) return id
120 unmodified lines
modified:package.json+1 added-1 removed