parent
6d9aaef18c
commit
c4dcdff984
3 changed files with 42 additions and 3 deletions
@ -0,0 +1,38 @@ |
|||||||
|
export default class HintKeyProducer { |
||||||
|
private charset: string; |
||||||
|
|
||||||
|
private counter: number[]; |
||||||
|
|
||||||
|
constructor(charset: string) { |
||||||
|
if (charset.length === 0) { |
||||||
|
throw new TypeError('charset is empty'); |
||||||
|
} |
||||||
|
|
||||||
|
this.charset = charset; |
||||||
|
this.counter = []; |
||||||
|
} |
||||||
|
|
||||||
|
produce(): string { |
||||||
|
this.increment(); |
||||||
|
|
||||||
|
return this.counter.map(x => this.charset[x]).join(''); |
||||||
|
} |
||||||
|
|
||||||
|
private increment(): void { |
||||||
|
let max = this.charset.length - 1; |
||||||
|
if (this.counter.every(x => x === max)) { |
||||||
|
this.counter = new Array(this.counter.length + 1).fill(0); |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
this.counter.reverse(); |
||||||
|
let len = this.charset.length; |
||||||
|
let num = this.counter.reduce((x, y, index) => x + y * len ** index) + 1; |
||||||
|
for (let i = 0; i < this.counter.length; ++i) { |
||||||
|
this.counter[i] = num % len; |
||||||
|
num = ~~(num / len); |
||||||
|
} |
||||||
|
this.counter.reverse(); |
||||||
|
} |
||||||
|
} |
||||||
|
|
@ -1,9 +1,10 @@ |
|||||||
import HintKeyProducer from 'content/hint-key-producer'; |
import HintKeyProducer from '../../../src/content/usecases/HintKeyProducer'; |
||||||
|
import { expect } from 'chai'; |
||||||
|
|
||||||
describe('HintKeyProducer class', () => { |
describe('HintKeyProducer class', () => { |
||||||
describe('#constructor', () => { |
describe('#constructor', () => { |
||||||
it('throws an exception on empty charset', () => { |
it('throws an exception on empty charset', () => { |
||||||
expect(() => new HintKeyProducer([])).to.throw(TypeError); |
expect(() => new HintKeyProducer('')).to.throw(TypeError); |
||||||
}); |
}); |
||||||
}); |
}); |
||||||
|
|
Reference in new issue