Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created August 16, 2022 10:28
Show Gist options
  • Save andreasvirkus/109b0cf343486939b7d7897aaa81c0fc to your computer and use it in GitHub Desktop.
Save andreasvirkus/109b0cf343486939b7d7897aaa81c0fc to your computer and use it in GitHub Desktop.

Revisions

  1. andreasvirkus created this gist Aug 16, 2022.
    11 changes: 11 additions & 0 deletions roundingThatScales.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    const roundingStops = [5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000]

    export const roundToScale = (count, scale = roundingStops) => {
    if (count === 0) return 0

    const nearestIdx = scale.findIndex((s) => s > count)
    let nearest = scale[nearestIdx]
    if (nearestIdx !== 0 && nearest / 2 > count) nearest = scale[nearestIdx - 1] || scale[0]

    return nearest || count
    }