6/2/2018 - 11:47 AM

Clamp Value

Function that clamps a value between optional arguments min_val and max_val.

def clamp(val, min_val=None, max_val=None):
  # swap min and max if wrong way round.
  if min_val is not None and max_val is not None and max_val < min_val:
    min_val, max_val = max_val, min_val
  if min_val is not None:
    val = max([val, min_val])
  if max_val is not None:
    val = min([val, max_val])
  return val