Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active May 17, 2020 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/1b0fa1f771509b5bdb7634ae02c32ecb to your computer and use it in GitHub Desktop.
Save XoseLluis/1b0fa1f771509b5bdb7634ae02c32ecb to your computer and use it in GitHub Desktop.
Avoid to overfill the stack, part 2
function transformString (source){
if (source.length === 0)
return "";
if (source.length === 1)
return source.toUpperCase() + source;
let curItem = source[0];
let transformed = transformString(source.substring(1));
return curItem.toUpperCase() + transformed + curItem;
}
let st = "helloworld";
console.log(transformString(st));
function transformStringWithTimeout (source, counter = 0, postActions, resFn){
let curItem;
let postAction = transformed => curItem.toUpperCase() + transformed + curItem;
//initial call
if (resFn === undefined){
var pr = new Promise((res, rej) => resFn = res);
postActions = [];
}
//end recursion
if (source.length === 1){
let initValue = source.toUpperCase() + source;
//using reduceRight to run the stack of actions
let result = postActions.reduceRight((accum, fn) => fn(accum), initValue);
resFn(result);
}
else{
curItem = source[0];
postActions.push(postAction);
if (counter < 5){
transformStringWithTimeout(source.substring(1), ++counter, postActions, resFn);
}
else{
//let's release the stack
setTimeout(() => {
console.log("timeout handling");
transformStringWithTimeout(source.substring(1), 0, postActions, resFn);
}, 0);
}
}
return pr;
}
(async () => {
console.log("-- with timeout");
let result = await transformStringWithTimeout("helloworld");
console.log(result);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment