library-ts/browser/random/IncrementalIDGenerator.ts

68 lines
1.5 KiB
TypeScript

import { RandomEngine } from "./RandomEngine";
import { JSRandomEngine } from "./JSRandomEngine";
export class IncrementalIDGenerator
{
static readonly LETTERS_CHARACTER_SET =
"ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyz";
static readonly BASE_62_CHARACTER_SET =
"ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyz0123456789";
static readonly BASE_64_URL_CHARACTER_SET =
"ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyz0123456789-_";
static readonly BASE_64_CHARACTER_SET =
"ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyz0123456789+/";
private _set = IncrementalIDGenerator.BASE_64_URL_CHARACTER_SET;
private _state:number[] = [];
constructor( set:string = null )
{
this._set = set || IncrementalIDGenerator.BASE_64_URL_CHARACTER_SET;
}
setState( state:number[] )
{
this._state = state;
}
private _incrementAt( position:number )
{
if ( position >= this._state.length )
{
this._state.push( 0 );
}
else if ( this._state[ position ] === ( this._set.length - 1 ) )
{
this._state[ position ] = 0;
this._incrementAt( position + 1 );
}
else
{
this._state[ position ] ++;
}
}
private _getID()
{
let id = "";
for ( let i = 0; i < this._state.length; i++ )
{
id += this._set[ this._state[ i ] ];
}
return id;
}
createID()
{
this._incrementAt( 0 );
return this._getID();
}
}