Search code examples
mathcompass-sasssass

Max to 0 to Max algorithm


First off, let me warn you that my Maths knowledge is fairly limited (hence my coming here to ask about this).

It's a silly example, but what I essentially want is to have a variable number of rows, and be able to set a maximum value, then for each progressive row decrease that value until half way at which point start increasing the value again back up to the maximum by the final row.

To illustrate this... Given that: maxValue = 20, and rows = 5, I need to be able to get to the following values for the row values (yes, even the 0):

row 1: 20
row 2: 10
row 3: 0
row 4: 10
row 5: 20

There are limitations though because I'm trying to do this in Compass which uses SASS. See here for the available operations, but to give you the gist of it, only basic operations are available.

I'm able to loop through the rows, so just need the calculation that will work for each individual row in the series. This is the kind of loop I'm able to use:

$maxValue:20;
$rows:5;

@for $i from 1 through $rows {
    // calculation here.
}

Solution

  • I haven't really worked with SASS before, but try something like this using a basic if and the floor function, not sure if will work

    // set various variables
    $maxValue:20;
    $rows:5;
    // get row number before middle row, this instance it will be 2
    $middleRow = floor( $maxValue / $rows )
    // get increment amount, this instance should be 10
    $decreaseValue = ( max / floor( rows / 2) )
    
    @for $i from 0 through $rows - 1 {
    
       @if $i <= $middleRow {
    
          ( $maxValue- ( $decreaseValue * $i ) )
    
        }
    
       @else{
    
        // times by -1 to make positive value
           ( $maxValue - ( $decreaseValue * -$i ) ) * -1
    
        }
    }
    

    I have tested the above in js ( with relative syntax ) and it yielded the required results ( jsBin example ). Hope this helps