5 ms·
Decades ago, a closure in Forth was especially innovative with DOES>: : COUNTER CREATE , DOES> DUP 1 SWAP +! @ ; 0 COUNTER PK PK . \ => 1 PK .
by oneearedrabbit 1y ago
Decades ago, a closure in Forth was especially innovative with DOES>:
: COUNTER
CREATE ,
DOES> DUP 1 SWAP +! @ ;
0 COUNTER PK
PK . \ => 1
PK . \ => 2
A semi-equivalent in Javascript is:
const counter = init => {
let x = init;
return () => { x += 1; return x; };
};
const pk = counter(0);
console.log(pk()); // => 1
console.log(pk()); // => 2