String / code / id sequential generator.
Generator function that produces a sequence of IDs.
Most sequential ID generators need you to start from the first ID, but this one alows you to easily pass the current ID (that you might have retrieved from a DB) and generate the next ones with an instant performance.
The sequence is based on a list of characters (sequence parameter) and has the lenght based on an initial ID (initialOrLength parameter when a string is passed) or on a length o characters (initialOrLength parameter when a number is passed).
A generator function can be iterated with a 'for of', that will return the next ID for each iteration or can be called using "next()", that will return an object like { value: <the ID>, done: <boolean that is true when the sequence is finished> }
.
npm i sequential-id-generator
The function has two parameters: initialOrLength and sequence.
initialOrLength (default = 5)
The initial ID string if you want to start the generation from a certain point or the length of the ID to start from the first ID.
Example:
initialOrLength = '00' will produce a sequence from '01' on. The passed current ID is skipped.
initialOrLength = 2 will start from '00', as the sequence will start from the beginning of the sequence with the specified length.
sequence (default = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
The string with the sequence of characters to produce the IDs. The order of the characters mather to the result.
import generator from './index'
let ids = idGenerator('28')
ids.next() // { value: '29', done: false }
ids.next() // { value: '2A', done: false }
ids.next() // { value: '2B', done: false }
ids = idGenerator('ZZ')
ids.next() // { value: undefined, done: true }
ids = idGenerator(2, '01')
ids.next() // { value: '00', done: false }
ids.next() // { value: '01', done: false }
ids.next() // { value: '10', done: false }
ids.next() // { value: '11', done: false }
ids.next() // { value: undefined, done: true }
ids = idGenerator('4', '0123456')
for (const str of ids) {
console.log(str)
} // '5', '6'
ids = idGenerator(2, '012')
for (const str of ids) {
console.log(str)
} // '00', '01', '02', '10', '11', '12', '20', '21', '22'
Working version but with performance issues for large IDs due to how the generator was constructed sequentially, going through every ID before the passed one.
Improved ID generator can now continue to the next ID without going through all previous IDs. The code is also muche easier to understand how the next ID is being generated.
Fixed package instalation for projects without TS.