My solution to challenge 2 in this series
Instructions:
In Santa's workshop, the elves have a list of gifts they want to make and a limited set of materials.
The gifts are strings and the materials are characters. Your task is to write a function that, given a list of gifts and the available materials, returns a list of gifts that can be manufactured.
A gift can be manufactured if we have all the necessary materials to make it.
const gifts = ['tren', 'oso', 'pelota']
const materials = 'tronesa'
manufacture(gifts, materials) // ["train", "bear"]
// 'train' YES because its letters are in 'tronesa'
// 'bear' YES because its letters are in 'tronesa'
// 'ball' NO because its letters are NOT in 'tronesa'
const gifts = ['juego', 'puzzle']
const materials = 'jlepuz'
manufacture(gifts, materials) // ["puzzle"]
const gifts = ['libro', 'ps5']
const materials = 'psli'
manufacture(gifts, materials) // []
Solution
function manufacture(gifts, materials) {
const materialsSet = new Set(materials);
const lettersInWord = (word) => {
return word.split('').filter(letter => materialsSet.has(letter)).join('');
};
return gifts.filter(gift => gift.length === lettersInWord(gift).length);
}
- Create a Set that separates all the letters from materials.
- Create an auxiliary function
lettersInWord
that takes a word, splits it into letters (using.split()
), filters the letters based on whether they belong to thematerialsSet
previously defined, and finally joins them back into a string. - The final step is to apply a filter on the
gifts
array and return only those elements whose length is equal to the length of the word returned by thelettersInWord
function.
Solution
Top comments (0)