Message from JavaScript discussions
July 2017
— Alright thanks alot
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for reference :) it is a nifty function :)
— Thank you
— Welcome ^-^
— Also .indexOf accepts a start argument
— How do u mean?
—
"use strict";
function findNames(text, name, start = 0) {
const hits = [];
const hit = text.indexOf(name, start);
const end = hit + name.length;
if (hit !== -1) {
hits.push(text.substring(start, end));
findNames(text, name, end)
.forEach(result =>
hits.push(result));
}
return hits;
}
const text = "Valentine, Valentine, Valentine, Valentine, Valentine, Valentine.";
const myName = "Valentine";
console.log(findNames(text, myName));
— Logs:
[ 'Valentine',
', Valentine',
', Valentine',
', Valentine',
', Valentine',
', Valentine' ]
— Recursion ❤️
— Valentine
— Hrmm
— This could be optimized to be tail-recursive