Skip to content

Instantly share code, notes, and snippets.

@Beraliv
Last active January 6, 2018 20:42
Show Gist options
  • Save Beraliv/1f3a8120c1236108fab557d5d96149c4 to your computer and use it in GitHub Desktop.
Save Beraliv/1f3a8120c1236108fab557d5d96149c4 to your computer and use it in GitHub Desktop.
Word Games and methods to work with combinations: contains, starts and ends.
// TODO:
// 1) optimise search by sorting strings
/*
* words: Factory for finding words
*
* letters: String or Array,
* length: Number,
*/
const words = (() => {
const flatMap = arr => arr.reduce((flatArr, elem) => [...flatArr, ...elem], []);
const exclude = (arr, fromArr) => {
const map = new Set(arr);
return fromArr.filter(elem => !map.has(elem));
};
const includes = (arr, inArr) => {
const map = new Set(inArr);
return arr.every(elem => map.has(elem));
};
return ({ letters, length }) => {
const sortedLetters = [...letters].sort();
const iteration = arr => flatMap(
arr.map(word => exclude(word, sortedLetters).map(char => [...word, char]))
);
const mapper = (arr, len) => len === 1
? arr
: mapper(iteration(arr), len - 1);
const possibleWords = mapper(sortedLetters, length).map(arr => arr.join(''));
return {
find: ({
contains = '',
starts = '',
ends = '',
} = {}) => {
const filters = [
word => includes([...contains], word),
word => word.startsWith(starts),
word => word.endsWith(ends),
];
return possibleWords.filter(
word => filters.every(f => f(word))
);
}
};
};
})();
// Game 1
const game1 = words({
letters: [...'foring'],
length: 4,
});
console.log(
game1.find({
contains: [...'fong'],
}),
game1.find({
starts: 'for',
}),
game1.find({
ends: 'for',
}),
);
// Game 2
const game2 = words({
letters: 'foring',
length: 4,
});
console.log(
game2.find({
contains: 'fong',
}),
game2.find({
starts: 'for',
}),
game2.find({
ends: 'for',
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment