diff --git a/samples/calc-02/index.js b/samples/calc-02/index.js index cf4ccef..8b1ff4a 100644 --- a/samples/calc-02/index.js +++ b/samples/calc-02/index.js @@ -58,7 +58,7 @@ const functionKeys = [ { label: '1/x', action: 'recip', className: 'key-default' }, { label: '%', action: 'mod', className: 'key-default' }, { label: '√x', action: 'sqrt', className: 'key-default' }, - { label: 'y√x', action: 'pow', className: 'key-default' }, + { label: 'y√x', action: 'root', className: 'key-default' }, { label: '10ˣ', action: 'pow10', className: 'key-default' }, { label: '', spacer: true }, { label: 'log', action: 'log', className: 'key-default' }, diff --git a/src/rpn-calculator.js b/src/rpn-calculator.js index 27a6055..9311f0d 100644 --- a/src/rpn-calculator.js +++ b/src/rpn-calculator.js @@ -46,6 +46,20 @@ class RpnCalculator { aliases: ['^', 'y^x'], execute: (calc, a, b) => Math.pow(a, b), }, + root: { + category: 'Arithmetic', + argCount: 2, + aliases: ['y√x', 'yroot', 'nroot'], + execute: (calc, a, b) => { + if (b === 0) { + throw new Error('Invalid input for root'); + } + if (a < 0 && b % 2 === 0) { + throw new Error('Invalid input for root'); + } + return Math.pow(a, 1 / b); + }, + }, sqr: { category: 'Arithmetic', argCount: 1, @@ -178,7 +192,7 @@ class RpnCalculator { static getOperationsByCategory() { return { Stack: ['dup', 'drop', 'swap', 'clear', 'enter'], - Arithmetic: ['add', 'sub', 'mul', 'div', 'mod', 'pow', 'sqr', 'neg', 'sqrt', 'recip', 'log', 'ln'], + Arithmetic: ['add', 'sub', 'mul', 'div', 'mod', 'pow', 'root', 'sqr', 'neg', 'sqrt', 'recip', 'log', 'ln'], Trigonometry: ['sin', 'cos', 'tan', 'asin', 'acos', 'atan'], }; }