Advanced Type Checking

This collection of functions is for testing if the value of a variable is of a certain type. For instance, is 13rem a relative length? TRUE! Is "frosty the snowman" and integer? FALSE!

This is likely most useful for advanced mixin and framework creators who aim to make their code more fault tolerant.

////
// A collection of function for advanced type checking
// @author Hugo Giraudel
////

@function is-number($value) {
  @return type-of($value) == 'number';
}
 
@function is-time($value) {
  @return is-number($value) and index('ms' 's', unit($value)) != null;
}
 
@function is-duration($value) {
  @return is-time($value);
}
 
@function is-angle($value) {
  @return is-number($value) and index('deg' 'rad' 'grad' 'turn', unit($value)) != null;
}
 
@function is-frequency($value) {
  @return is-number($value) and index('Hz' 'kHz', unit($value)) != null;
}
 
@function is-integer($value) {
  @return is-number($value) and round($value) == $value;
}
 
@function is-relative-length($value) {
  @return is-number($value) and index('em' 'ex' 'ch' 'rem' 'vw' 'vh' 'vmin' 'vmax', unit($value)) != null;
}
 
@function is-absolute-length($value) {
  @return is-number($value) and index('cm' 'mm' 'in' 'px' 'pt' 'pc', unit($value)) != null;
}
 
@function is-percentage($value) {
  @return is-number($value) and unit($value) == '%';
}
 
@function is-length($value) {
  @return is-relative-length($value) or is-absolute-length($value);
}
 
@function is-resolution($value) {
  @return is-number($value) and index('dpi' 'dpcm' 'dppx', unit($value)) != null;
}
 
@function is-position($value) {
  @return is-length($value) or is-percentage($value) or index('top' 'right' 'bottom' 'left' 'center', $value) != null;
}

Comments

  1. User Avatar
    Joseph Fusco
    Permalink to comment#

    Thanks Hugo!

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag