Menu

Post image 1
Post image 2
1 / 2
0

Recreating Math.floor without the Math object? Here is my manual approach.

DEV Community·Aaron Brown·23 days ago
#mNXzMdvk
Reading 0:00
15s threshold

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 ?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More