feat: add dynamic constant management to the calculator core
This commit is contained in:
@@ -2,6 +2,9 @@ class RpnCalculator {
|
||||
static CONSTANTS = {
|
||||
pi: Math.PI,
|
||||
e: Math.E,
|
||||
phi: (1 + Math.sqrt(5)) / 2,
|
||||
g: 9.80665,
|
||||
c: 299792458,
|
||||
};
|
||||
|
||||
static OPERATIONS = {
|
||||
@@ -212,6 +215,15 @@ class RpnCalculator {
|
||||
this.enabledCommands = new Set(selectedCommands.map((name) => this.normalizeCommandName(name)).filter((name) => RpnCalculator.OPERATIONS[name]));
|
||||
}
|
||||
|
||||
static isValidConstantName(name) {
|
||||
return typeof name === 'string' && name.trim() !== '';
|
||||
}
|
||||
|
||||
static isReservedName(name) {
|
||||
const normalized = typeof name === 'string' ? name.toLowerCase() : '';
|
||||
return Boolean(RpnCalculator.OPERATIONS[normalized]);
|
||||
}
|
||||
|
||||
toRadians(value) {
|
||||
if (this.angleMode === 'grad') {
|
||||
return (value * Math.PI) / 200;
|
||||
@@ -257,6 +269,45 @@ class RpnCalculator {
|
||||
return typeof name === 'string' && Object.prototype.hasOwnProperty.call(this.constants, name.toLowerCase());
|
||||
}
|
||||
|
||||
setConstant(name, value) {
|
||||
if (!RpnCalculator.isValidConstantName(name)) {
|
||||
throw new Error('Invalid constant name');
|
||||
}
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error('Invalid constant value');
|
||||
}
|
||||
|
||||
const normalized = name.trim().toLowerCase();
|
||||
if (RpnCalculator.isReservedName(normalized)) {
|
||||
throw new Error(`Constant name conflicts with a command: ${name}`);
|
||||
}
|
||||
|
||||
this.constants[normalized] = value;
|
||||
return value;
|
||||
}
|
||||
|
||||
removeConstant(name) {
|
||||
if (!RpnCalculator.isValidConstantName(name)) {
|
||||
throw new Error('Invalid constant name');
|
||||
}
|
||||
|
||||
const normalized = name.trim().toLowerCase();
|
||||
if (!this.isConstantName(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
delete this.constants[normalized];
|
||||
return true;
|
||||
}
|
||||
|
||||
hasConstant(name) {
|
||||
if (!RpnCalculator.isValidConstantName(name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.isConstantName(name.trim().toLowerCase());
|
||||
}
|
||||
|
||||
push(value) {
|
||||
if (this.stack.length >= this.maxSize) {
|
||||
throw new Error('Stack overflow');
|
||||
@@ -408,6 +459,10 @@ class RpnCalculator {
|
||||
getConstants() {
|
||||
return { ...this.constants };
|
||||
}
|
||||
|
||||
listConstants() {
|
||||
return this.getConstants();
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
|
||||
Reference in New Issue
Block a user