Trying to create a function that returns a function and returned function will provide the individual characters of the string passed to the original function on its invocations. When the end of the string is met, it will start back at the beginning.
Example: 'cat' should return: 'c' (on the first invocation) 'a' (on the second invocation) 't' (on the third) 'c' (should then return back to beginning)
Here is the code that I have thus far:
function individualChar (str) {
let individualStr = str;
let invoked = 0;
return function () {
if (invoked > 0) {
let char = individualStr.slice(0);
invoked++
return `${char}`;
}
return individualStr;
}
}
My thought process was having the individualStr assigned to the str argument along with creating an 'invoked' counter. Then in the returned function, creating the 'char' variable and assigning that to the individualStr and slice it at the first character (0), to take it out, and then have an invoke counter to invoke the function as needed.
However, as of right now, it's still only returning the entire string.
I thought about maybe using a while loop as well, to keep track of the number of invocations, but I wasn't sure if that would be best approach for this.
Any guidance would be appreciated!
Via Active questions tagged javascript - Stack Overflow https://ift.tt/qdnex3V
Comments
Post a Comment