HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Mathematical boundaries (audio meter)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
meteraudioboundariesmathematical

Problem

I've just been putting together an audio meter by stacking bootstrap progress bars, and thought there was probably a better way, mathematically / logically, of achieving this.

levels = (vumeter) ->
  green = if vumeter % 50 < vumeter then 50 else vumeter
  yellow = if vumeter % 85 < vumeter then 35 else vumeter - 50
  red = if vumeter % 100 < vumeter then 15 else vumeter - 85

  'green': green
  'yellow': yellow
  'red': red

Solution

vumeter % 50 50, so you can just use that instead. For negative numbers, this will always return false, although it seems like this would be an illegal argument to your function.

@mleyfman provided a great solution. In practice, the code provided achieves something called clamping, where you restrict a value to a specified range. You can roll your own clamp function like so:

clamp = (value, min, max) -> Math.min(Math.max(min, value), max)

levels = (vumeter) ->
  'green'  : clamp(vumeter,  0,  50)
  'yellow' : clamp(vumeter, 50,  85) - 50
  'red'    : clamp(vumeter, 85, 100) - 85
  // or, if you find it more meaningful to provide maxima as parameters rather than ranges:
  'green': clamp(vumeter, 0, 50)
  'yellow': clamp(vumeter - 50, 0, 35)
  'red': clamp(vumeter - 85, 0, 15)

Code Snippets

clamp = (value, min, max) -> Math.min(Math.max(min, value), max)

levels = (vumeter) ->
  'green'  : clamp(vumeter,  0,  50)
  'yellow' : clamp(vumeter, 50,  85) - 50
  'red'    : clamp(vumeter, 85, 100) - 85
  // or, if you find it more meaningful to provide maxima as parameters rather than ranges:
  'green': clamp(vumeter, 0, 50)
  'yellow': clamp(vumeter - 50, 0, 35)
  'red': clamp(vumeter - 85, 0, 15)

Context

StackExchange Code Review Q#59916, answer score: 4

Revisions (0)

No revisions yet.