Skip to content

Instantly share code, notes, and snippets.

@alexandrzavalii
Last active April 25, 2021 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandrzavalii/b0a8e6bf2c7ab3bcfc59edd5d11ccdd7 to your computer and use it in GitHub Desktop.
Save alexandrzavalii/b0a8e6bf2c7ab3bcfc59edd5d11ccdd7 to your computer and use it in GitHub Desktop.
Alpha numeric id generator
class AlphaNumericIdGenerator {
constructor() {
const alpha = Array.from({ length: 26 }, (_, i) => String.fromCharCode(i + 97))
const numo = Array.from({ length: 10 }, (_, i) => i.toString())
this.alphanumeric = numo.concat(alpha)
this.alphaIndx = this.alphanumeric.reduce((obj, cur, i) => ({ ...obj, [cur]: i }), {});
}
between(after, before) {
this._validate(after);
this._validate(before);
if(before <= after) {
throw new Error('before has to be bigger then after')
}
const valuesBetween = [];
while(after < before && valuesBetween.length < 100000){
valuesBetween.push(before);
before = this.increment(before,-1)
}
const mid = Math.floor(valuesBetween.length/2)
if(valuesBetween.length <= 1) return false;
return valuesBetween[mid];
}
_validate(val){
if(typeof val !== 'string' || val<'0' || val>'zzzzzzzzz' || val.length>9) {
throw new Error('Must be string between "a" and "zzzzzzzzz" ')
}
}
after(after) {
this._validate(after);
return this.between(after,'zzzzzzzzz')
}
before(before) {
this._validate(before);
return this.between('0',before)
}
increment(val, incrementer) {
let nextVal = val.split('');
let i = val.length-1
for(;i>=0 && incrementer !== 0; i--){
const cur = nextVal[i];
if(cur === 'z' && incrementer === 1){
nextVal[i] = '0';
} else if(cur === '0' && incrementer === -1){
nextVal[i] = 'z';
} else {
const idx = this.alphaIndx[cur]
nextVal[i] = this.alphanumeric[idx+incrementer];
incrementer = 0
}
}
nextVal = nextVal.join('')
if(incrementer === 1){
nextVal = val + '0';
}
if(incrementer === -1){
nextVal = val.slice(1)
}
return nextVal;
}
}
let stringGenerator = new AlphaNumericIdGenerator();
let a = ['0', '01']
let id = stringGenerator.between(...a);
let idAfter = stringGenerator.after(a[1]);
let idBefore = stringGenerator.before(a[1]);
// a.push(id);
a.push(idAfter);
a.push(idBefore);
a.sort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment