Verified Commit 04b08024 authored by Florent Chehab's avatar Florent Chehab
Browse files

feat(frontend utils): created counter class

* also added tests
parent 01265070
/**
* Helper class just like the one in python
*/
class Counter {
/**
* @param {Iterable} elements
*/
constructor(elements) {
const res = new Map();
elements.forEach(el => {
if (!res.has(el)) {
res.set(el, 0);
}
res.set(el, res.get(el) + 1);
});
/**
* @type {Map<any, number>}
*/
this.res = res;
}
/**
* return the keys that have duplicates
* @returns {Array.<any>}
*/
getDuplicatedElements() {
return [...this.res.entries()]
.filter(([, count]) => count > 1)
.map(([key]) => key);
}
}
export default Counter;
import Counter from "./counter";
test("Count nothing empty string", () => {
const counter = new Counter([]);
expect(counter.res).toMatchObject(new Map());
});
test("Count one element", () => {
const counter = new Counter(["coucou"]);
expect(counter.res).toMatchObject(new Map([["coucou", 1]]));
});
test("Count twice element", () => {
const counter = new Counter(["coucou", "coucou"]);
expect(counter.res).toMatchObject(new Map([["coucou", 2]]));
});
test("Count two elements diff", () => {
const counter = new Counter(["coucou", "coucou", "test"]);
expect(counter.res).toMatchObject(new Map([["coucou", 2], ["test", 1]]));
});
test("Test show duplicated", () => {
const counter = new Counter(["coucou", "coucou", "test"]);
expect(counter.getDuplicatedElements()).toMatchObject(["coucou"]);
});
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment