It’s a challenge that requests that we create a subLength() function that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.
Now, I’ve tried to do it a certain way that I found on MDN and I really liked, but I receive an error. I will try to do it in another way, so please don’t tell me another way to do it, I just would like to know why is this not accepted, and if it’s something I should worry about in the future when I work as a developer.
Having said so, this is what I tried:
/ Write function below
const subLength = (string, charact) => {
const appears = [...string.matchAll(charact)];
if (appears.length < 2 || appears.length > 2){
return 0;
} else if (appears.length === 2){
return appears[1].index - appears[0].index + 1;
} else {
return 'There has been an error with the input!';
}
};
console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0
And this is the error stack trace:
/home/ccuser/workspace/assessment-5f8754a6e91ae500128deb08/main.js:3
const appears = [...string.matchAll(charact)];
^
TypeError: string.matchAll(...)[Symbol.iterator] is not a function
at subLength (/home/ccuser/workspace/assessment-5f8754a6e91ae500128deb08/main.js:3:32)
at Object.<anonymous> (/home/ccuser/workspace/assessment-5f8754a6e91ae500128deb08/main.js:15:13)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
Now, the interesting part is: both Studio Code (Node) and Browser Console (JS) accept this and throw the output expected. The problem is only making it work on CodeCademy. Why?
NOTES:
The error in the stack trace is a TypeError because of the iterator. Now, I reviewed the documentation in MDN and the compatibility of matchAll() should not be the problem since it’s been in Node (used in CodeCademy’s console emulation, right?) ever since 12.0, but Node is now in 15+, 14+ being the safer recommended.
I also checked the same documentation page this specific usage of a spread operator (available for Node since 5.0) but there is an example that is very similar. You can check in the matchAll() page linked above, just above the compatibility table and you’ll see.
Thus, once again, why does this error happen and why only in CodeCademy while it does not occur in browser console nor in Visual Studio Code?
Or even… can I untangle it (without using any other method to achieve this)?
Thanks in advance!