@lucadani7/algonodejs-for-beginners
Version:
Just a simple Node.js package with some basic algorithms perfect for people just starting out. It's got easy-to-understand TypeScript versions of stuff like sorting, searching, math with numbers, and messing with strings.
47 lines (46 loc) • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumeralSystem = void 0;
class NumeralSystem {
static isValid(value, base) {
const pattern = new RegExp(`^[0-9A-Fa-f]+$`);
if (!pattern.test(value)) {
return false;
}
for (const char of value.toUpperCase()) {
const digit = parseInt(char, 16);
if (isNaN(digit) || digit >= base) {
return false;
}
}
return true;
}
static convert(value, fromBase, toBase) {
if (!this.isValid(value, fromBase)) {
throw new Error(`Invalid value '${value}' for base ${fromBase}`);
}
const decimal = BigInt(parseInt(value, fromBase));
return decimal.toString(toBase).toUpperCase();
}
static toBinary(value, fromBase) {
return this.convert(value, fromBase, 2);
}
static toOctal(value, fromBase) {
return this.convert(value, fromBase, 8);
}
static toDecimal(value, fromBase) {
return this.convert(value, fromBase, 10);
}
static toHex(value, fromBase) {
return this.convert(value, fromBase, 16);
}
static add(a, b, base) {
const sum = BigInt(parseInt(a, base)) + BigInt(parseInt(b, base));
return sum.toString(base).toUpperCase();
}
static subtract(a, b, base) {
const diff = BigInt(parseInt(a, base)) - BigInt(parseInt(b, base));
return diff.toString(base).toUpperCase();
}
}
exports.NumeralSystem = NumeralSystem;