Skip to content

Commit

Permalink
memoize without touching the argument function
Browse files Browse the repository at this point in the history
  • Loading branch information
Dierk Koenig committed Dec 13, 2024
1 parent dee984c commit b36de83
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 11 deletions.
10 changes: 5 additions & 5 deletions docs/src/examples/sequence/Collatz.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,21 @@ <h1>Collatz</h1>
import { memoize } from "../../kolibri/util/memoize.js";
import { dom, select } from "../../kolibri/util/dom.js";

const collatzSeq = n =>
let collatz = n =>
n < 2
? Seq(1)
: n % 2 === 0
? memCollatz( n / 2 ) .cons(n)
: memCollatz( n * 3 + 1 ).cons(n)
? collatz( n / 2 ) .cons(n)
: collatz( n * 3 + 1 ).cons(n)
;
const memCollatz = memoize(collatzSeq);
collatz = memoize(collatz);

const [input] = select(document.body, "#input");
const [out] = select(document.body, "#out");

input.onchange = _e => {
const n = Number(input.value);
const seq = memCollatz(n);
const seq = collatz(n);
const [table] = dom(`
<table>
<tr>
Expand Down
6 changes: 3 additions & 3 deletions docs/src/kolibri/util/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ const { debug } = LoggerFactory("ch.fhnw.kolibri.util.memoize");
* The cache hit count is logged on {@link LOG_DEBUG} level.
* @type { <_T_, _U_> (f: Functor<_T_,_U_>) => Functor<_T_,_U_> }
* @example
* const fib = n => n < 2 ? 1 : memFib(n-1) + memFib(n-2);
* const memFib = memoize(fib);
* memFib(10);
let fib = n => n < 2 ? 1 : fib(n-1) + fib(n-2);
fib = memoize(fib);
fib(2) // is 2
*/
const memoize = f => {
const cache = new Map();
Expand Down
6 changes: 3 additions & 3 deletions docs/src/kolibri/util/memoizeTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { memoize } from "./memoize.js";
const memoizeSuite = TestSuite("util/memoize");

const makeFib = () => {
const fib = n => n < 2 ? 1 : memFib(n-1) + memFib(n-2);
const memFib = memoize(fib);
return memFib;
let fib = n => n < 2 ? 1 : fib(n-1) + fib(n-2);
fib = memoize(fib);
return fib;
};

// this must come first or the logging numbers spill over
Expand Down

0 comments on commit b36de83

Please sign in to comment.