Skip to content

Commit

Permalink
fix collision by proxy number
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Jan 11, 2022
1 parent 3b56634 commit 398fd90
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Expand Up @@ -23,7 +23,7 @@ let fillPool = bytes => {
}

let random = bytes => {
fillPool(bytes)
fillPool((bytes -= 0))
return pool.subarray(poolOffset - bytes, poolOffset)
}

Expand Down Expand Up @@ -65,7 +65,7 @@ let customRandom = (alphabet, size, getRandom) => {
let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)

let nanoid = (size = 21) => {
fillPool(size)
fillPool((size -= 0))
let id = ''
// We are reading directly from the random pool to avoid creating new array
for (let i = poolOffset - size; i < poolOffset; i++) {
Expand Down
38 changes: 38 additions & 0 deletions test/index.test.js
Expand Up @@ -151,5 +151,43 @@ for (let type of ['node', 'browser']) {
}
})
})

if (type === 'node') {
describe('proxy number', () => {
it('prevent collision', () => {
let makeProxyNumberToReproducePreviousID = () => {
let step = 0
return {
valueOf() {
// // if (!pool || pool.length < bytes) {
if (step === 0) {
step++
return 0
}

// } else if (poolOffset + bytes > pool.length) {
if (step === 1) {
step++
return -Infinity
}

// poolOffset += bytes
if (step === 2) {
step++
return 0
}

return 21
}
}
}

let ID1 = nanoid()
let ID2 = nanoid(makeProxyNumberToReproducePreviousID())

expect(ID1).not.toBe(ID2)
})
})
}
})
}

0 comments on commit 398fd90

Please sign in to comment.