Menu

Post image 1
Post image 2
1 / 2
0

The percentage helpers I wish someone had handed me on day one of JavaScript

DEV Community·levent çelik·about 1 month ago
#pAJ8f8pB
Reading 0:00
15s threshold

Percentages are the math operation programmers re-invent the most. Every checkout flow has them, every dashboard has them, every pricing toggle has them, and yet I still see the same three off-by-one bugs in code reviews every month. Most of them come down to one thing: nobody wrote a small set of named helpers, so every component invents its own. Here are the five percentage helpers I keep in a percent.ts file. None of them are clever. All of them have saved me at least one bug. 1. percent of value The one everyone gets right: export const percentOf = ( value : number , percent : number ): number => ( value * percent ) / 100 ; percentOf ( 250 , 8.5 ); // 21.25 Enter fullscreen mode Exit fullscreen mode But having it as a named function means your sales tax calculation reads as percentOf(price, taxRate) instead of (price * taxRate) / 100 repeated in 14 components. Less typing is the smaller win; the bigger one is that any bug you find lives in exactly one place. The canonical use case is sales tax.…

Continue reading — create a free account

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

Read More