Skip to content

Instantly share code, notes, and snippets.

@cahnory
Created October 2, 2015 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cahnory/9a369674a1ed9e894386 to your computer and use it in GitHub Desktop.
Save cahnory/9a369674a1ed9e894386 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
<div class="box"></div>
// ----
// libsass (v3.2.5)
// ----
// Memoization
// didn't really try with multiple inputs ^^
@function memoize($getter, $inputs...) {
$value: null;
@if memoize-has($getter, $inputs) {
$value: memoize-get($getter, $inputs);
}
@else {
$value: memoize-set($getter, $inputs);
}
@return $value;
}
// "private" functions
@function memoize-has($getter, $inputs) {
@return map-has-key($MEMOIZE__STORE, $getter)
and map-has-key(map-get($MEMOIZE__STORE, $getter), '#{$inputs}');
}
@function memoize-get($getter, $inputs) {
@return map-get(map-get($MEMOIZE__STORE, $getter), '#{$inputs}');
}
@function memoize-set($getter, $inputs) {
$value: call($getter, $inputs...);
$MEMOIZE__STORE: map-merge(
$MEMOIZE__STORE,
(
$getter: map-merge(
map-get($MEMOIZE__STORE, $getter) or (),
('#{$inputs}': $value)
)
)
)!global;
@return $value;
}
$MEMOIZE__STORE: ()!default;
/* fibonacci example */
$_fibonacci: 0;
@function _fibonacci($i) {
// count each call
$_fibonacci: $_fibonacci + 1!global;
$i: round(abs($i));
@if $i < 2 {
@return $i;
}
@return fibonacci($i - 1) + fibonacci($i - 2);
}
@function fibonacci($i) {
@return memoize('_fibonacci', $i);
}
memoized {
/* res, exe */
@for $i from 0 through 5 {
φ: fibonacci($i), $_fibonacci;
}
}
@charset "UTF-8";
/* fibonacci example */
memoized {
/* res, exe */
φ: 0, 1;
φ: 1, 2;
φ: 1, 3;
φ: 2, 4;
φ: 3, 5;
φ: 5, 6;
}
<div class="box"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment