parent
13fb726332
commit
f1c920e000
2 changed files with 58 additions and 0 deletions
@ -0,0 +1,33 @@ |
|||||||
|
export default class HintKeyProducer { |
||||||
|
constructor(charset) { |
||||||
|
if (charset.length === 0) { |
||||||
|
throw new TypeError('charset is empty'); |
||||||
|
} |
||||||
|
|
||||||
|
this.charset = charset; |
||||||
|
this.counter = []; |
||||||
|
} |
||||||
|
|
||||||
|
produce() { |
||||||
|
this.increment(); |
||||||
|
|
||||||
|
return this.counter.map((x) => this.charset[x]).join(''); |
||||||
|
} |
||||||
|
|
||||||
|
increment() { |
||||||
|
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(); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,25 @@ |
|||||||
|
import { expect } from "chai"; |
||||||
|
import HintKeyProducer from '../../src/content/hint-key-producer'; |
||||||
|
|
||||||
|
describe('HintKeyProducer class', () => { |
||||||
|
describe('#constructor', () => { |
||||||
|
it('throws an exception on empty charset', () => { |
||||||
|
expect(() => new HintKeyProducer([])).to.throw(TypeError); |
||||||
|
}); |
||||||
|
}); |
||||||
|
|
||||||
|
describe('#produce', () => { |
||||||
|
it('produce incremented keys', () => { |
||||||
|
let charset = 'abc'; |
||||||
|
let sequences = [ |
||||||
|
'a', 'b', 'c', |
||||||
|
'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', |
||||||
|
'aaa', 'aab', 'aac', 'aba'] |
||||||
|
|
||||||
|
let producer = new HintKeyProducer(charset); |
||||||
|
for (let i = 0; i < sequences.length; ++i) { |
||||||
|
expect(producer.produce()).to.equal(sequences[i]); |
||||||
|
} |
||||||
|
}); |
||||||
|
}); |
||||||
|
}); |
Reference in new issue