The best / efficient way to remember the last result of a function
I am used to using bind
functions and tracking to remember the last result so that I can use the last result for the next result. For example, to concatenate or append the last line to a new line without using external variables:
function remStr(outStr){
return function c(lastStr,newStr){
if(!newStr)return lastStr;
var all = lastStr+newStr;
return c.bind(null,all);
}.bind(null,outStr);
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
The problem is that I want to call remStr
multiple times and so bind
came into play. But can it be done better or otherwise, maybe it turns out that for one case the approach performs the task better than remStr
?
source to share
If I understand your intent correctly, how about using a closure?
function remStr(outStr) {
return function c(newStr) {
if (!newStr) return outStr;
outStr += newStr;
return c;
}
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
As Tomalak mentioned in the comments , JavaScript strings are immutable, so if you intend to use large or many strings, you probably want to buffer them in an array.
function remStr(outStr) {
var buffer = [outStr || ''];
return function c(newStr) {
if (!newStr) return buffer.join('');
buffer.push(newStr);
return c;
}
}
var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow
source to share
You shouldn't be using it Function.bind
here at all. You can cache arguments. And then join him.
This approach is widely known because functions are also objects and can have properties. Function.bind
is used to change the context of a given function, and that's not what we want.
function concat(word){
return function fn(anWord){
if(!anWord) return fn.words.join("");
(fn.words || (fn.words = [word])).push(anWord);
}
}
Now you can use it like below:
var str = concat("stack");
str("over");
str("flow");
console.log(str()); // "stackoverflow"
source to share