The task is to replicate the Math.pow() function, with the powers only integers.
The boilerplate code
function pow(base, power){
// your code here
}
If the power is 0, return 1
if (power === 0) return 1
Multiply the base by the absolute value of the power, taking negative powers into consideration
let result = 1;
let absPower = Math.abs(power);
for (let i = 0; i < absPower; i++) {
result *= base;
}
If the power is negative, return the reciporcal. Otherwise, return the result
return power > 0 ? result : 1 / result;
The final code
function pow(base, power){
// your code here
if(power === 0) return 1;
let result = 1;
let absPower = Math.abs(power);
for(let i = 0; i < absPower; i++) {
result *= base;
}
return power > 0 ? result : 1 / result;
}
That's all folks!
Top comments (0)