From 997cb06a7f38a2cdaf0124f9a60f00bfc8e3882e Mon Sep 17 00:00:00 2001 From: helloShen Date: Mon, 7 Feb 2022 20:54:14 -0500 Subject: [PATCH] Add another version of power() function --- calculator/calculator.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/calculator/calculator.js b/calculator/calculator.js index 78e4a6f..f295a39 100644 --- a/calculator/calculator.js +++ b/calculator/calculator.js @@ -20,6 +20,23 @@ const power = function(a, b) { return Math.pow(a, b); }; +/* + * If you want to write a handmade power() function by yourself, + * Here's a simple example. + * Only work with integer as input. + */ +const intPower = function(base, exponent) { + if (exponent === 0) return 1; + if (base === 0) return (exponent > 0)? 0 : Infinity; + let result = 1; + if (exponent > 0) { + while (exponent-- > 0) result *= base; + } else { + while (exponent++ < 0) result /= base; + } + return result; +}; + const factorial = function(n) { if (n < 0) return undefined; if (n === 0) return 1;