Last active
August 29, 2015 13:57
-
-
Save chriseppstein/9883370 to your computer and use it in GitHub Desktop.
Memoization in Sass
This file contains hidden or 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
// This approach lets you generically memoize any function by changing the call site: | |
@function something-slow-to-compute($arg-1, $arg-2) { | |
@return ... slow calculation ... ; | |
} | |
$cached-values: (); | |
@function cached($function-name, $args...) { | |
$cached-value: map-get($cached-values, ($function-name, $args)); | |
@if $cached-value { | |
@return $cached-value; | |
} @else { | |
$result: call($function-name, $args...); | |
$cached-values: map-merge($cached-values, (($function-name, $args): $result)) !global; | |
@return $result; | |
} | |
} | |
.output { | |
slow-call: cached(something-slow-to-compute, 100, 500); | |
fast-call: cached(something-slow-to-compute, 100, 500); // the second call is fast | |
} |
This file contains hidden or 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
// This approach lets you memoize the results for all callers of this function. | |
$slow-computation-results: (); | |
@function something-slow-to-compute($arg-1, $arg-2) { | |
$cached-value: map-get($slow-computation-results, ($arg-1, $arg-2)); | |
@if $cached-value { | |
@return $cached-value; | |
} @else { | |
$result: ... slow calculation ... ; | |
$slow-computation-results: map-merge($slow-computation-results, (($arg-1, $arg-2): $result)) !global; | |
@return $result; | |
} | |
} | |
.output { | |
slow-call: something-slow-to-compute(100, 500); | |
fast-call: something-slow-to-compute(100, 500); // the second call is fast | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment