Dynamic scope (emulation) in JavaScript
Chances are, you never heard of dynamic scoping.
But it is similar to other familliar concepts:
- *nix environment variables (ones you get from
process.env
) - JavaScript's
this
(barely, but still) - Global constants, except you can override them at call site
const d = require('@futpib/d');
function log(s) {
const { output } = d.scope;
output.write(s);
}
d.const({ output: process.stdin }, () => {
log('hello');
// Writes "hello" to standard input
});
d.const({ output: process.stderr }, () => {
log('world');
// Writes "world" to standard error
});
const fs = require('fs');
const logToFile = d.bind({ output: fs.createWriteStream('log.txt') }, log);
logToFile('fluff');
// Writes "fluff" to 'log.txt' in current directory
yarn add @futpib/d
or
npm install @futpib/d
Keeping d.const
and d.bind
-created function calls outside tight loops seems like a good idea.
Check out index.benchmark.js.
Run via yarn benchmark
.
- Common Lisp's defparameter and defvar