Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

keeping the value in javascript closure

I need to implement a stringBuilder which can called multiple times, for the first call, stringBuilder returns a function which should store the previous value, in other calls it’s returnign value depends on the argument, if there isn’t any argument it returns a string which consists of all the previous calls, but if it has an argument it should return a new function to store the next string, but every step should be able call sperately. here is an example:

const stringBuilder = (str) => {
  let result = str;
  return (newStr) => {
    if (typeof newStr == 'undefined') return result;
    else {
      result += newStr;
      return stringBuilder(result)
    }
  }
}

const hello = stringBuilder('hello');
const helloWorld = hello(' world');
const helloWorldJS = helloWorld(' JS');

console.log(hello()); // I expect the result should be 'hello'
console.log(helloWorld()); // I expect the result should be 'hello world'
console.log(helloWorldJS());

Any help would be appreciated. Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need to store the previous values in result variable, you can concat previous string with new string and calling again stringBuilder, like this:

const stringBuilder = (str)=> {
    return (newStr)=> newStr ? stringBuilder(str + newStr) : str;
}
const hello = stringBuilder('hello');
const helloWorld = hello(' world');
const helloWorldJS = helloWorld(' JS');
const helloWorldStackoverflow = helloWorld(' stackoverflow');

console.log(hello());
console.log(helloWorld());
console.log(helloWorldJS());
console.log(helloWorldStackoverflow());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading