-
Notifications
You must be signed in to change notification settings - Fork 0
/
scramble.ts
33 lines (29 loc) · 969 Bytes
/
scramble.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
* Returns true when all the letters of 'otherword'
* are contained within 'word'.
* e.g.
*
* scramble('foo', 'bar') -> false
* scramble('foobar', 'bar') -> true
* scramble('rkqodlw', 'world') -> true
* scramble('cedewaraaossoqqyt', 'codewars') -> true
*
* (Yes, this is originally from CodeWars)
*
* scramble('katas', 'steak') -> false
*
* Note: The final solution *should consider performance*
*
*/
export const scramble = (word: string, otherWord: string): boolean => {
const otherWordArray = otherWord.split('')
const initialState: { word: string, otherWord: string, hasFoundLetters: boolean[] } =
{ word, otherWord, hasFoundLetters: [] }
otherWordArray.reduce((state, nextLetter) => {
state.hasFoundLetters.push(state.word.includes(nextLetter))
state.word = otherWord.split('').filter(match => match !== state.word)
}, initialState)
return otherWordArray.every(letter => {
return word.includes(letter)
})
}