-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#14.js
More file actions
57 lines (48 loc) · 1.25 KB
/
#14.js
File metadata and controls
57 lines (48 loc) · 1.25 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Reto #14: 🗃️ Encuentra el camino al regalo
*
* Ejemplos
*/
const workshop = {
storage: {
shelf: {
box1: 'train',
box2: 'switch'
},
box: 'car'
},
gift: 'doll'
}
findGiftPath(workshop, 'train')
// ➜ ['storage', 'shelf', 'box1']
findGiftPath(workshop, 'switch')
// ➜ ['storage', 'shelf', 'box2']
findGiftPath(workshop, 'car')
// ➜ ['storage', 'box']
findGiftPath(workshop, 'doll')
// ➜ ['gift']
findGiftPath(workshop, 'plane')
// ➜ []
/**
* @param {object} workshop - A representation of the workshop
* @param {string|number|boolean} gift - The gift to find
* @returns {number[]} The path to the gift
*/
function findGiftPath(workshop, gift) {
for (const key in workshop) {
// 1. ¿Lo encontramos directamente?
if (workshop[key] === gift) {
return [key];
}
// 2. Si es un objeto, profundizamos (Recursividad)
if (typeof workshop[key] === 'object' && workshop[key] !== null) {
const subPath = findGiftPath(workshop[key], gift);
// Si la llamada recursiva devuelve un array con contenido, lo encontramos ahí
if (subPath.length > 0) {
return [key, ...subPath];
}
}
}
// 3. Si terminamos el bucle y no está, devolvemos array vacío
return [];
}