
// stringify the given arg

-string(arg)
  type(arg) + ' ' + arg

// require a color

require-color(color)
  unless color is a 'color' 
    error('RGB or HSL value expected, got a ' + -string(color))

// require a unit

require-unit(n)
  unless n is a 'unit'
    error('unit expected, got a ' + -string(n))

// require a string

require-string(str)
  unless str is a 'string' or str is a 'ident'
    error('string expected, got a ' + -string(str))

// apply js Math function

math(n, fn) 
  require-unit(n)
  require-string(fn)
  -math(n, fn)

// adjust the given color's property by amount

adjust(color, prop, amount)
  require-color(color)
  require-string(prop)
  require-unit(amount)
  -adjust(color, prop, amount)

// Math functions

abs(n) { math(n, 'abs') }
ceil(n) { math(n, 'ceil') }
floor(n) { math(n, 'floor') }
round(n) { math(n, 'round') }
min(a, b) { a < b ? a : b }
max(a, b) { a > b ? a : b }

// return the sum of the given numbers

sum(nums)
  sum = 0
  sum += n for n in nums

// return the average of the given numbers

avg(nums)
  sum(nums) / length(nums)

// color components

alpha(color) { component(hsl(color), 'alpha') }
hue(color) { component(hsl(color), 'hue') }
saturation(color) { component(hsl(color), 'saturation') }
lightness(color) { component(hsl(color), 'lightness') }

// check if n is an odd number

odd(n)
  1 == n % 2

// check if n is an even number

even(n)
  0 == n % 2

// check if color is light

light(color)
  lightness(color) >= 50%

// check if color is dark

dark(color)
  lightness(color) < 50%

// desaturate color by amount

desaturate(color, amount)
  adjust(color, 'saturation', - amount)

// saturate color by amount

saturate(color, amount)
  adjust(color, 'saturation', amount)

// darken by the given amount

darken(color, amount)
  adjust(color, 'lightness', - amount)

// lighten by the given amount

lighten(color, amount)
  adjust(color, 'lightness', amount)

// increase the current lightness value by the given amount

lighten-by(color, amount)
  l = lightness(color)
  l = 100 if 0 == l
  adjust(color, 'lightness', l * amount / 100)

// decrease the current lightness value by the given amount

darken-by(color, amount)
  l = lightness(color)
  adjust(color, 'lightness', - (l * amount / 100))

// return the last value in the given expr

last(expr)
  expr[length(expr) - 1]

// join values with the given delimiter

join(delim, vals...)
  buf = ''
  vals = vals[0] if length(vals) == 1
  for val, i in vals
    buf += i ? delim + val : val
