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.
>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());