Skip to content

Instantly share code, notes, and snippets.

@rogeriochaves

rogeriochaves/index.js

Last active Jan 26, 2021
Embed
What would you like to do?
const thiagoWay = (lista) => {
let ar = lista.map((el) => el.name);
let array_elements = ar.sort();
let current = null;
let cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
delete lista[i].id;
if (array_elements[i] != current) {
current = array_elements[i];
cnt = 1;
lista[i].quantity = cnt;
} else {
cnt++;
lista[i].quantity = cnt;
}
}
return lista;
};
const sortWay = (list) => {
const names = list.map((el) => el.name).sort();
let current;
let count = 0;
let result = [];
let j = -1;
for (let i in names) {
if (names[i] != current) {
count = 1;
j += 1;
} else {
count++;
}
result[j] = result[j] || { name: names[i] };
result[j].quantity = count;
current = names[i];
}
return result;
};
const nestedMapsAndFiltersWay = (list) =>
list
.map((item) => ({
name: item.name,
quantity: list.filter((x) => x.name === item.name).length,
}))
.reduce(
(acc, curr) => {
if (acc.set.has(curr.name)) {
return acc;
}
return { set: acc.set.add(curr.name), result: [...acc.result, curr] };
},
{ set: new Set(), result: [] }
).result;
const mapWay = (list) => {
const result = {};
for (const item of list) {
const { name } = item;
result[name] = result[name] || { name, quantity: 0 };
result[name].quantity++;
}
return Object.values(result);
};
const reduceWay = (list) =>
Object.values(
list.reduce((result, current) => {
const { name } = current;
result[name] = result[name] || { name, quantity: 0 };
result[name].quantity++;
return result;
}, {})
);
const reduceWayImmutable = (list) =>
Object.values(
list.reduce((result, current) => {
const { name } = current;
if (result[name]) {
return {
...result,
[name]: { ...result[name], quantity: result[name].quantity + 1 },
};
}
return { ...result, [name]: { name, quantity: 1 } };
}, {})
);
module.exports = {
thiagoWay,
sortWay,
nestedMapsAndFiltersWay,
mapWay,
reduceWay,
reduceWayImmutable,
};
const { describe, it, expect } = require("@jest/globals");
const {
thiagoWay,
sortWay,
nestedMapsAndFiltersWay,
mapWay,
reduceWay,
reduceWayImmutable,
} = require("./index");
describe("groupings", () => {
it("sorts in various ways", () => {
const input = [
{ id: 1, name: "A" },
{ id: 2, name: "B" },
{ id: 3, name: "A" },
{ id: 4, name: "A" },
{ id: 5, name: "B" },
{ id: 6, name: "C" },
];
const expected = [
{ name: "A", quantity: 3 },
{ name: "B", quantity: 2 },
{ name: "C", quantity: 1 },
];
// expect(thiagoWay([...input])).toEqual(expected); // nao funciona
expect(sortWay(input)).toEqual(expected);
expect(nestedMapsAndFiltersWay(input)).toEqual(expected);
expect(mapWay(input)).toEqual(expected);
expect(reduceWay(input)).toEqual(expected);
expect(reduceWayImmutable(input)).toEqual(expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment