Skip to content

Instantly share code, notes, and snippets.

@chrisross
Last active March 3, 2016 11:55
Show Gist options
  • Save chrisross/5936025 to your computer and use it in GitHub Desktop.
Save chrisross/5936025 to your computer and use it in GitHub Desktop.
This sass extension utilises the Greated Common Divisor (gcd) algorithm to reduce duplicate styles, especially when making your own grid system.
#!/usr/bin/env ruby
# To implement extension, run this command in a shell:
# $ sass -i -r ./gcd_sass_extension.rb
# Or require it in compass config
# require './gcd_sass_extension'
module Sass::Script::Functions
#
# Uses the 'greatest common divisor' algorithm to work out if a fraction
# (represented by the method arguments) can be simplified further. Which is
# useful for batch generation of unique fractions without duplicates (.e.g
# 1/2 and 2/4, etc.), such as grid system class names.
#
# @param num_1 [Integer] The numerator of the fraction
# @param num_1 [Integer] The denominator of the fraction
#
# @return [Integer] The greatest common divisor, divide both numerator
# and denominator by this to find the simplified fraction
def gcd num_1, num_2
num_1 = num_1.value if num_1.respond_to?(:value)
num_2 = num_2.value if num_2.respond_to?(:value)
if num_2 == 0
Sass::Script::Number.new num_1
else
gcd num_2, num_1%num_2
end
end
declare :gcd, :args => [:number, :number]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment