CyberChef/src/core/operations/Base.js

67 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-11-28 11:42:58 +01:00
/**
* Numerical base operations.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @namespace
*/
const Base = {
2016-11-28 11:42:58 +01:00
/**
* @constant
* @default
*/
DEFAULT_RADIX: 36,
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* To Base operation.
*
* @param {number} input
* @param {Object[]} args
* @returns {string}
*/
runTo: function(input, args) {
2016-11-28 11:42:58 +01:00
if (!input) {
throw ("Error: Input must be a number");
}
2017-04-13 19:08:50 +02:00
const radix = args[0] || Base.DEFAULT_RADIX;
2016-11-28 11:42:58 +01:00
if (radix < 2 || radix > 36) {
throw "Error: Radix argument must be between 2 and 36";
}
return input.toString(radix);
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* From Base operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {number}
*/
runFrom: function(input, args) {
2017-04-13 19:08:50 +02:00
const radix = args[0] || Base.DEFAULT_RADIX;
2016-11-28 11:42:58 +01:00
if (radix < 2 || radix > 36) {
throw "Error: Radix argument must be between 2 and 36";
}
2017-04-13 19:08:50 +02:00
let number = input.replace(/\s/g, "").split("."),
result = parseInt(number[0], radix) || 0;
if (number.length === 1) return result;
// Fractional part
2017-04-13 19:08:50 +02:00
for (let i = 0; i < number[1].length; i++) {
const digit = parseInt(number[1][i], radix);
result += digit / Math.pow(radix, i+1);
}
return result;
2016-11-28 11:42:58 +01:00
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
};
export default Base;