Aaron BrownEver tried to solve a problem while someone tied your hands behind your back? I recently took on a...
Ever tried to solve a problem while someone tied your hands behind your back? I recently took on a challenge to rebuild JavaScript's rounding methods without using any of the built in Math functions, no bitwise operators, and not even the % operator.It sounds easy until you realize how many shortcuts we take for granted.
The Logic:
Finding the Floor, the biggest hurdle was performance. If you just loop 1 by 1 from zero, you'll crash the browser on large numbers. I decided to use a "fast-forward" while loop to jump by 100,000 at a time before using a for loop to find the exact integer.Here is the full implementation I came up with:
function floor(num) {
if (num >= 0) {
let i = 0
while(num > i+100000){
i = i+100000
}
for (i; ; i++) {
if (i + 1 > num) return i
}
} else {
for (let i = 0; ; i--) {
if (i <= num) return i
}
}
}
function ceil(num) {
let f = floor(num)
return f === num ? num : f + 1
}
function trunc(num) {
return num >= 0 ? floor(num) : ceil(num)
}
function round(num) {
if (num >= 0) {
return num - floor(num) >= 0.5 ? ceil(num) : floor(num)
} else {
return num - floor(num) >= 0.5 ? ceil(num) : floor(num)
}
}
Breakdown of the approach:
The "Big Jump":
In the floor function, I used while(num > i+100000) to skip through huge ranges. This keeps the execution time low even for values in the millions.
*Infinite Loops for recision: *
I used for(i; ; i++) without a middle condition. Since I know I’ll eventually hit a number larger than num, the if statement handles the return and breaks the loop safely.
Reusability:
Once floor was solid, ceil and trunc became easy extensions. They just lean on the core logic of finding that base integer.
Why do this?
It’s easy to call Math.round() and move on. But building it manually makes you think about how numbers are actually stored and compared. It's a great exercise in control flow and manual optimization.How would you have handled the jump logic? Would you go bigger than 10,000? Comment below! 👇