Skip to content

Commit 724eaa1

Browse files
authored
Merge pull request #21 from marcode24/2024-03
✨ Add challenge-03 solution
2 parents d7b1adc + 84a42d6 commit 724eaa1

File tree

4 files changed

+192
-0
lines changed

4 files changed

+192
-0
lines changed
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Reto 03: Organizando-el-inventario
2+
3+
Santa Claus 🎅 está revisando el inventario de su taller para preparar la entrega de regalos. Los elfos han registrado los juguetes en un array de objetos, pero la información está un poco desordenada. **Necesitas ayudar a Santa a organizar el inventario.**
4+
5+
Recibirás un array de objetos, donde **cada objeto representa un juguete y tiene las propiedades:**
6+
7+
- name: el nombre del juguete (string).
8+
- quantity: la cantidad disponible de ese juguete (entero).
9+
- category: la categoría a la que pertenece el juguete (string).
10+
11+
Escribe una función que procese este array y devuelva un objeto que organice los juguetes de la siguiente manera:
12+
13+
- Las claves del objeto serán las categorías de juguetes.
14+
- Los valores serán objetos que tienen como claves los nombres de los juguetes y como valores las cantidades totales de cada juguete en esa categoría.
15+
- Si hay juguetes con el mismo nombre en la misma categoría, debes sumar sus cantidades.
16+
- Si el array está vacío, la función debe devolver un objeto vacío {}.
17+
18+
```js
19+
const inventary = [
20+
{ name: 'doll', quantity: 5, category: 'toys' },
21+
{ name: 'car', quantity: 3, category: 'toys' },
22+
{ name: 'ball', quantity: 2, category: 'sports' },
23+
{ name: 'car', quantity: 2, category: 'toys' },
24+
{ name: 'racket', quantity: 4, category: 'sports' }
25+
]
26+
27+
organizeInventory(inventary)
28+
29+
// Resultado esperado:
30+
// {
31+
// toys: {
32+
// doll: 5,
33+
// car: 5
34+
// },
35+
// sports: {
36+
// ball: 2,
37+
// racket: 4
38+
// }
39+
40+
const inventary2 = [
41+
{ name: 'book', quantity: 10, category: 'education' },
42+
{ name: 'book', quantity: 5, category: 'education' },
43+
{ name: 'paint', quantity: 3, category: 'art' }
44+
]
45+
46+
organizeInventory(inventary2)
47+
48+
// Resultado esperado:
49+
// {
50+
// education: {
51+
// book: 15
52+
// },
53+
// art: {
54+
// paint: 3
55+
// }
56+
// }
57+
```
58+
59+
## Mi solución explicada
60+
61+
```js
62+
function organizeInventory(inventory) {
63+
return inventory.reduce(
64+
(result, { category, name, quantity }) => (
65+
(result[category] ??= {}),
66+
(result[category][name] = ~~result[category][name] + quantity),
67+
result
68+
),
69+
{},
70+
);
71+
}
72+
```
73+
74+
Primero utilizamos el método `reduce` para recorrer el array de objetos y obtener un objeto final. El objeto final será el resultado de organizar el inventario.
75+
76+
```js
77+
inventory.reduce(
78+
(result, { category, name, quantity }) => (
79+
(result[category] ??= {}),
80+
(result[category][name] = ~~result[category][name] + quantity),
81+
result
82+
),
83+
{},
84+
);
85+
```
86+
87+
Dentro de la función de reducción, desestructuramos cada objeto en sus propiedades `category`, `name` y `quantity`. Luego, actualizamos el objeto `result` con la información del juguete actual.
88+
89+
```js
90+
(result[category] ??= {}),
91+
(result[category][name] = ~~result[category][name] + quantity),
92+
result
93+
```
94+
95+
Para organizar el inventario, primero verificamos si la categoría ya existe en el objeto `result`. Si no existe, la inicializamos como un objeto vacío.
96+
97+
```js
98+
(result[category] ??= {})
99+
```
100+
101+
Luego, actualizamos la cantidad del juguete en la categoría correspondiente. Para ello, sumamos la cantidad actual del juguete con la cantidad del juguete actual.
102+
103+
Para evitar problemas con valores `undefined`, utilizamos el operador de doble negación `~~` para convertir `undefined` en `0` y sumar la cantidad actual.
104+
105+
Para saber más sobre el operador de doble negación, puedes consultar la siguiente [documentación](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT).
106+
107+
```js
108+
(result[category][name] = ~~result[category][name] + quantity)
109+
```
110+
111+
Finalmente, devolvemos el objeto `result` actualizado en cada iteración.
112+
113+
```js
114+
result
115+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/* eslint-disable no-bitwise */
2+
/* eslint-disable no-sequences */
3+
function organizeInventory(inventory) {
4+
return inventory.reduce(
5+
(result, { category, name, quantity }) => (
6+
(result[category] ??= {}),
7+
(result[category][name] = ~~result[category][name] + quantity),
8+
result
9+
),
10+
{},
11+
);
12+
}
13+
14+
module.exports = organizeInventory;
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
const organizeInventory = require('./index');
2+
3+
describe('03 => Organizando-el-inventario', () => {
4+
const TEST_CASES = [
5+
{
6+
input: [],
7+
output: {},
8+
},
9+
{
10+
input: [{ name: 'doll', quantity: 5, category: 'toys' }],
11+
output: { toys: { doll: 5 } },
12+
},
13+
{
14+
input: [
15+
{ name: 'book', quantity: 10, category: 'education' },
16+
{ name: 'book', quantity: 5, category: 'education' },
17+
{ name: 'paint', quantity: 3, category: 'art' },
18+
],
19+
output: {
20+
education: {
21+
book: 15,
22+
},
23+
art: {
24+
paint: 3,
25+
},
26+
},
27+
},
28+
{
29+
input: [
30+
{ name: 'doll', quantity: 5, category: 'toys' },
31+
{ name: 'car', quantity: 3, category: 'toys' },
32+
{ name: 'ball', quantity: 2, category: 'sports' },
33+
{ name: 'car', quantity: 2, category: 'toys' },
34+
{ name: 'racket', quantity: 4, category: 'sports' },
35+
],
36+
output: {
37+
toys: {
38+
doll: 5,
39+
car: 5,
40+
},
41+
sports: {
42+
ball: 2,
43+
racket: 4,
44+
},
45+
},
46+
},
47+
];
48+
49+
it('should return an object', () => {
50+
const { input } = TEST_CASES[0];
51+
const result = organizeInventory(input);
52+
expect(typeof result).toBe('object');
53+
});
54+
55+
it.each(TEST_CASES)(
56+
'should return the expected value',
57+
({ input, output }) => {
58+
const result = organizeInventory(input);
59+
expect(result).toEqual(output);
60+
},
61+
);
62+
});

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ npm run test 'year'/'challenge'/index.test.js
6161
| :-: | ------------------------------------------------------------------------------------------- | :--------: | :--------------------------------------------------------------------------------------------------------: | :-----------: |
6262
| 01 | [🎁 ¡Primer regalo repetido!](https://adventjs.dev/es/challenges/2024/1) | 🟢 | [here](./2024/01-primer-regalo-repetido/index.js) | ⭐⭐⭐⭐⭐ |
6363
| 02 | [🖼️ Enmarcando nombres](https://adventjs.dev/es/challenges/2024/2) | 🟢 | [here](./2024/02-enmarcando-nombres/index.js) | ⭐⭐⭐⭐⭐ |
64+
| 03 | [🏗️ Organizando el inventario](https://adventjs.dev/es/challenges/2024/3) | 🟢 | [here](./2024/03-organizando-el-inventario/index.js) | ⭐⭐⭐⭐⭐ |
6465

6566
Difficulties legend:
6667
🟢 Easy 🟡 Medium 🔴 Hard

0 commit comments

Comments
 (0)