Find All Possible Recipes from Given Supplies LeetCode solution in JavaScript

1
var findAllRecipes = function (recipes, ingredients, supplies) {
2
const setOfIngredients = new Set(supplies);
3
const recipesWithIngredients = new Map();
4
const progress = new Map();
5
//map recipes to it's ingredients and set each recipe to false in another map called progress
6
for (let i = 0; i < recipes.length; i++) {
7
recipesWithIngredients.set(recipes[i], ingredients[i]);
8
progress.set(recipes[i], false);
9
}
10

11
const result = [];
12

13
for (const rec of recipes) {
14
if (recurse(rec, recipesWithIngredients, setOfIngredients, progress)) {
15
result.push(rec);
16
setOfIngredients.add(rec);
17
}
18
}
19

20
return result;
21
};
22

23
function recurse(rec, recipesWithIngredients, setOfIngredients, progress) {
24
const currentIngredients = recipesWithIngredients.get(rec);
25
for (const ingredient of currentIngredients) {
26
if (setOfIngredients.has(rec)) continue;
27
if (setOfIngredients.has(ingredient)) continue;
28
else if (recipesWithIngredients.has(ingredient)) {
29
if (progress.get(ingredient)) return false;
30
progress.set(ingredient, true);
31
let hasCycle = recurse(
32
ingredient,
33
recipesWithIngredients,
34
setOfIngredients,
35
progress
36
);
37
if (!hasCycle) return false;
38
setOfIngredients.add(ingredient);
39
} else {
40
return false;
41
}
42
}
43
return true;
44
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0