Taken from DailyCodingProblem
Implement integer exponentiation. That is, implement the
pow(x, y)function, wherexandyare integers and returnsx^y.Do this faster than the native method of repeated multiplication.
Solution
This is the answer I came up with:
const exponent = (x: number, y: number): number => x ** y
const custom = (x: number, y: number): number => {
let result = x
for (let _ = 1; _ < y; _++) {
result *= x
}
return result
}Both functions handle exponentiation: the
exponentfunction does it using the exponential operator, and thecustomfunction implements it arithmetically. Thecustomfunction is probably the more correct answer, but both functions are faster when tested against the nativeMath.pow()method.