javascript - Best/efficent way to remember last function result -
i got used using bind
remember last result of function , keep track able use last result next result. instance concat or join last string new string without using outer variables:
function remstr(outstr){ return function c(laststr,newstr){ if(!newstr)return laststr; var = laststr+newstr; return c.bind(null,all); }.bind(null,outstr); } var str = remstr('stack'); str = str('over'); str = str('flow'); str(); // stackoverflow
the problem want call remstr
several times , bind
came play. can done better or differently, maybe turns out 1 case approach fulfills task better remstr
?
if understand intention correctly, how using 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 mentioned tomalak in comments, javascript strings immutable, if intend use large or many strings, want buffer them in 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
Comments
Post a Comment