Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created December 8, 2017 22:36
Show Gist options
  • Select an option

  • Save aire-con-gas/33fc91692b7169dd31cd5b6da56c8290 to your computer and use it in GitHub Desktop.

Select an option

Save aire-con-gas/33fc91692b7169dd31cd5b6da56c8290 to your computer and use it in GitHub Desktop.
Break up words in a string
const wordBreak = (text = '', validWords = []) => {
const wordLookupPos = {};
function breakUpWord (text, validWords, offset) {
if (wordLookupPos[offset]) {
return wordLookupPos[offset];
}
const resultArr = [];
console.log('offset', offset);
console.log('text.length', text.length);
if (offset === text.length) {
resultArr.push('');
}
for(let i = offset + 1; i <= text.length; i++) {
const rawSubString = text.substring(offset, i);
console.log('rawSubString', rawSubString);
if(validWords.includes(rawSubString)) {
const word = breakUpWord(text, validWords, i);
resultArr.push(rawSubString + (word === '' ? '' : ' ') + word);
}
}
return resultArr.join();
};
return breakUpWord(text, validWords, 0);
}
const wordDictionary = ["cats", "bag"];
console.log('>>> RESULT', wordBreak('bagcats', wordDictionary));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment