Sha256: a311a44acc7421ab26b9187aa6be2f7ae0248069cd5ef7c4dcee324f226b4bea
Contents?: true
Size: 1.46 KB
Versions: 54
Compression:
Stored size: 1.46 KB
Contents
const isValidBase = (base: number) => { return !base || base < 2 || Math.floor(base) !== base } const isInputValid = (array: number[], base: number) => { if (!array || !array.length) { return false } const val = base - 1 for (let i = 0, n = array.length; i < n; i++) { const tmp = array[i] if (tmp > val || tmp < 0) { return false } } return true } const convertFromDecimalToBase = (num: number, outputBase: number) => { let tmp = num const result = [] while (tmp) { result.unshift(tmp % outputBase) tmp = Math.floor(tmp / outputBase) } return result } export default class Converter { convert(array: number[], inputBase: number, outputBase: number) { if (isValidBase(inputBase)) { throw new Error('Wrong input base') } if (isValidBase(outputBase)) { throw new Error('Wrong output base') } const regexp = new RegExp('^0.', 'g') const str = array.join('') if (str.match(regexp) || !isInputValid(array, inputBase)) { throw new Error('Input has wrong format') } if (str === '0') { return [0] } if (str === '1') { return [1] } const decimalValue = array .reduce((accumulator, value) => accumulator * inputBase + value, 0) return convertFromDecimalToBase(decimalValue, outputBase) } }
Version data entries
54 entries across 54 versions & 1 rubygems