Add `clamp` as a built-in number function #402

Closed
wants to merge 1 commit into
from

Conversation

Projects
None yet
1 participant

A safeguard is very often needed when working with built-in functions, e.g, lighten, saturate, etc. where an $amount is expected to be between '0%' and '100%'.

Although it is trivial to implement in Sass using @-functions:

// Return a value between min and max.
@function clamp($value, $min, $max) {
  @return if($value > $max, $max, if($value < $min, $min, $value));
}

not every User is a Sass expert.

This commit defines a single clamp(..) function whose arguments are:

  • $value - the number being clamped
  • $min - the minimum allowed/accepted value
  • $max - the maximum allowed/accepted value

It behaves very much the same way as min(..) or max(..) and throws exceptions when arguments are not numbers or cannot be compared (tests included).

Example:

@import 'constants';

html {
  background: saturate($theme, clamp($base-exposure * 2, 0%, 100%));
  // ^ $theme and $base-exposure defined within '_constants.scss'.
}
Number function to return a value between min/max allowed.
A safeguard is very often needed when working with built-in functions,
e.g, `lighten`, `saturate`, etc. where an `$amount` is expected to be
between '0%' and '100%'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment