Photo by One Idea LLC on StockSnap
I have only recently now begun to use lambdas in a new way in my code. Not only is it a way to reduce the need for declared functions that you have to pass to another function and only get called once, they can also be put in place where you would normally have to have an expression that gives some value but wouldn't be able to use constants or variables. Finally, these things can be handy in getting rid of constants or variables with short-lived usefulness from scope. Consider this fragment:
const bufferTemplate = fs.readFileSync("./message.md");
const messageText = bufferTemplate.toString("utf-8");
const bufferTemplate2 = fs.readFileSync("./keys.json");
const keys = JSON.parse(bufferTemplate2.toString('utf-8'));
After these four lines, I really only want keys
and messageText
out of the four constants declared here.
We can eliminate one constant making bufferTemplate
a variable and recycling it.
let bufferTemplate = fs.readFileSync("./message.md");
const messageText = bufferTemplate.toString("utf-8");
bufferTemplate = fs.readFileSync("./keys.json");
const keys = JSON.parse(bufferTemplate.toString('utf-8'));
The variable, wont get eliminated from the scope however.
If I put it all in a block, I wont be able to access keys
or messageText
.
{
const bufferTemplate = fs.readFileSync("./message.md");
const messageText = bufferTemplate.toString("utf-8");
// The good news is bufferTemplate will get eliminated from scope
// outside of this code block. The bad news is, so will messageText!
}
In the above fragment, we need messageText
and putting it in a code block will eliminate it from scope. You need bufferTemplate to assign to messageText, so they have to go together here in the same scope.
Finally, using these lambdas in typescipt (or javascript or node), you can eliminate all of these single use constants without converting them into variables like this:
const successful_send_template: string = (() => {
const bufferTemplate = fs.readFileSync("./message.md");
return bufferTemplate.toString("utf-8");
})();
const keys : {'active': string, 'posting': string, account: string} = (() => {
const bufferTemplate = fs.readFileSync("./keys.json");
const p = JSON.parse(bufferTemplate.toString('utf-8'));
return p as {'active': string, 'posting': string, account: string};
})();
These lamdas can have several variables, they validate the data completely, throw exceptions, call other lambdas or call functions. Whatever happens, you end up with the only two constants you need and the rest go out of scope.