Created
December 8, 2017 22:36
-
-
Save aire-con-gas/33fc91692b7169dd31cd5b6da56c8290 to your computer and use it in GitHub Desktop.
Break up words in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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