Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions 2024/03-organizando-el-inventario/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Reto 03: Organizando-el-inventario

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.**

Recibirás un array de objetos, donde **cada objeto representa un juguete y tiene las propiedades:**

- name: el nombre del juguete (string).
- quantity: la cantidad disponible de ese juguete (entero).
- category: la categoría a la que pertenece el juguete (string).

Escribe una función que procese este array y devuelva un objeto que organice los juguetes de la siguiente manera:

- Las claves del objeto serán las categorías de juguetes.
- 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.
- Si hay juguetes con el mismo nombre en la misma categoría, debes sumar sus cantidades.
- Si el array está vacío, la función debe devolver un objeto vacío {}.

```js
const inventary = [
{ name: 'doll', quantity: 5, category: 'toys' },
{ name: 'car', quantity: 3, category: 'toys' },
{ name: 'ball', quantity: 2, category: 'sports' },
{ name: 'car', quantity: 2, category: 'toys' },
{ name: 'racket', quantity: 4, category: 'sports' }
]

organizeInventory(inventary)

// Resultado esperado:
// {
// toys: {
// doll: 5,
// car: 5
// },
// sports: {
// ball: 2,
// racket: 4
// }

const inventary2 = [
{ name: 'book', quantity: 10, category: 'education' },
{ name: 'book', quantity: 5, category: 'education' },
{ name: 'paint', quantity: 3, category: 'art' }
]

organizeInventory(inventary2)

// Resultado esperado:
// {
// education: {
// book: 15
// },
// art: {
// paint: 3
// }
// }
```

## Mi solución explicada

```js
function organizeInventory(inventory) {
return inventory.reduce(
(result, { category, name, quantity }) => (
(result[category] ??= {}),
(result[category][name] = ~~result[category][name] + quantity),
result
),
{},
);
}
```

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.

```js
inventory.reduce(
(result, { category, name, quantity }) => (
(result[category] ??= {}),
(result[category][name] = ~~result[category][name] + quantity),
result
),
{},
);
```

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.

```js
(result[category] ??= {}),
(result[category][name] = ~~result[category][name] + quantity),
result
```

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.

```js
(result[category] ??= {})
```

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.

Para evitar problemas con valores `undefined`, utilizamos el operador de doble negación `~~` para convertir `undefined` en `0` y sumar la cantidad actual.

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).

```js
(result[category][name] = ~~result[category][name] + quantity)
```

Finalmente, devolvemos el objeto `result` actualizado en cada iteración.

```js
result
```
14 changes: 14 additions & 0 deletions 2024/03-organizando-el-inventario/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable no-bitwise */
/* eslint-disable no-sequences */
function organizeInventory(inventory) {
return inventory.reduce(
(result, { category, name, quantity }) => (
(result[category] ??= {}),
(result[category][name] = ~~result[category][name] + quantity),
result
),
{},
);
}

module.exports = organizeInventory;
62 changes: 62 additions & 0 deletions 2024/03-organizando-el-inventario/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const organizeInventory = require('./index');

describe('03 => Organizando-el-inventario', () => {
const TEST_CASES = [
{
input: [],
output: {},
},
{
input: [{ name: 'doll', quantity: 5, category: 'toys' }],
output: { toys: { doll: 5 } },
},
{
input: [
{ name: 'book', quantity: 10, category: 'education' },
{ name: 'book', quantity: 5, category: 'education' },
{ name: 'paint', quantity: 3, category: 'art' },
],
output: {
education: {
book: 15,
},
art: {
paint: 3,
},
},
},
{
input: [
{ name: 'doll', quantity: 5, category: 'toys' },
{ name: 'car', quantity: 3, category: 'toys' },
{ name: 'ball', quantity: 2, category: 'sports' },
{ name: 'car', quantity: 2, category: 'toys' },
{ name: 'racket', quantity: 4, category: 'sports' },
],
output: {
toys: {
doll: 5,
car: 5,
},
sports: {
ball: 2,
racket: 4,
},
},
},
];

it('should return an object', () => {
const { input } = TEST_CASES[0];
const result = organizeInventory(input);
expect(typeof result).toBe('object');
});

it.each(TEST_CASES)(
'should return the expected value',
({ input, output }) => {
const result = organizeInventory(input);
expect(result).toEqual(output);
},
);
});
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ npm run test 'year'/'challenge'/index.test.js
| :-: | ------------------------------------------------------------------------------------------- | :--------: | :--------------------------------------------------------------------------------------------------------: | :-----------: |
| 01 | [🎁 ¡Primer regalo repetido!](https://adventjs.dev/es/challenges/2024/1) | 🟢 | [here](./2024/01-primer-regalo-repetido/index.js) | ⭐⭐⭐⭐⭐ |
| 02 | [🖼️ Enmarcando nombres](https://adventjs.dev/es/challenges/2024/2) | 🟢 | [here](./2024/02-enmarcando-nombres/index.js) | ⭐⭐⭐⭐⭐ |
| 03 | [🏗️ Organizando el inventario](https://adventjs.dev/es/challenges/2024/3) | 🟢 | [here](./2024/03-organizando-el-inventario/index.js) | ⭐⭐⭐⭐⭐ |

Difficulties legend:
🟢 Easy 🟡 Medium 🔴 Hard
Expand Down
Loading