Last active
August 29, 2015 13:57
-
-
Save micahgodbolt/9771802 to your computer and use it in GitHub Desktop.
Memoization Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---- | |
// Sass (v3.3.4) | |
// Compass (v1.0.0.alpha.18) | |
// ---- | |
//// Fibonacci Function | |
@function fibonacci($n) { | |
$fib: 0 1; | |
@for $i from 1 through nth($n,1) { | |
$new: nth($fib, length($fib)) + nth($fib, length($fib) - 1); | |
$fib: append($fib, $new); | |
} | |
@return $fib; | |
} | |
//// Create $memo map | |
$memo: (); | |
//// memo-update | |
@function memo-update($function, $params, $value) { | |
$result:(); | |
@if map-has-key($memo, $function) { | |
$sub-map-new: map-merge(map-get($memo,$function),($params: $value)); | |
$result: map-merge($memo, ($function: ($sub-map-new) )); | |
} | |
@else { | |
$result: map-merge($memo, ($function: ($params: $value))); | |
} | |
@return $result; | |
} | |
//// memo-get | |
@function memo-get($function, $params) { | |
$result: map-get(map-get($memo,$function),$params); | |
@return $result; | |
} | |
//// call-function | |
@function call-function($function, $params...) { | |
@if map-has-key($memo, $function) { | |
$result: memo-get($function, $params); | |
@if $result != null { | |
@return $result; | |
} | |
} | |
$result: call($function, $params...); | |
$memo: memo-update($function, $params, $result) !global; | |
@return $result; | |
} | |
//// | |
// Comment out function calls and uncomment memoization calls | |
// View difference in time to compile | |
//// | |
//// Traditional function calls ~1.5s | |
$fib1: fibonacci(1000); | |
$fib2: fibonacci(1000); | |
$fib3: fibonacci(1000); | |
//// Function calls made with memoization ~.5s | |
// $fib1: call-function(fibonacci, 1000); | |
// $fib2: call-function(fibonacci, 1000); | |
// $fib3: call-function(fibonacci, 1000); | |
div { | |
foo: inspect($fib1); | |
bar: inspect($memo); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment