Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Last active August 29, 2015 13:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/9883370 to your computer and use it in GitHub Desktop.
Save chriseppstein/9883370 to your computer and use it in GitHub Desktop.
Memoization in Sass
// 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 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