DEV Community

Cover image for Challenge 2 Advent JS 2023 by Midudev
Juneiker
Juneiker

Posted on

Challenge 2 Advent JS 2023 by Midudev

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) // []
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode
  1. Create a Set that separates all the letters from materials.
  2. Create an auxiliary function lettersInWord that takes a word, splits it into letters (using .split()), filters the letters based on whether they belong to the materialsSet previously defined, and finally joins them back into a string.
  3. 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 the lettersInWord function.

Solution Image

Solution

Previous Challenge Solutions

  1. Challenge 1 Advent JS 2023

Top comments (0)