-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
35 lines (32 loc) · 1.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* eslint-disable no-param-reassign */
const englishAlphabet = 'abcdefghijklmnopqrstuvwxyz';
function alphanumerize(num, options = this.options) {
// if num is options object, return a function with the alphabet preset
if (typeof num === 'object' && num !== null) return createInstance(num);
// conditions for an empty numeral sequence
if (typeof num !== 'number' || num === 0) return '';
// numeral sequences for negative numbers will start with a negative sign
let alphanumerals = '';
if (num < 0) {
num *= -1;
alphanumerals += '-';
}
// determine numeral sequence
const { alphabet } = options;
const base = alphabet.length;
const sequenceLength = Math.ceil(Math.log(1 - num / base + num) / Math.log(base));
for (let i = sequenceLength; i > 1; i -= 1) {
const power = base ** (i - 1);
const digit = Math.ceil(num / power) - 1;
alphanumerals += alphabet[digit - 1];
num -= digit * power; // calculate remainder
}
alphanumerals += alphabet[num - 1];
return alphanumerals;
}
function createInstance(options = {}) {
const instance = alphanumerize.bind({ options });
Object.defineProperty(instance, 'alphabet', { value: options.alphabet });
return instance;
}
module.exports = createInstance({ alphabet: englishAlphabet });