-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathexercise2.js
More file actions
76 lines (66 loc) · 1.96 KB
/
Copy pathexercise2.js
File metadata and controls
76 lines (66 loc) · 1.96 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// A utility module for data processing
function prc(arr, fn) {
const res = [];
const seen = new Map();
for (let i = 0; i < arr.length; i++) {
const key = fn(arr[i]);
if (!seen.has(key)) {
seen.set(key, true);
res.push(arr[i]);
}
}
return res;
}
function tfm(data, specs) {
return data.reduce((acc, item) => {
const group = specs.groupBy(item);
if (!acc[group]) {
acc[group] = { items: [], total: 0 };
}
acc[group].items.push(specs.transform(item));
acc[group].total += specs.getValue(item);
return acc;
}, {});
}
function vld(obj, rules) {
const errors = [];
for (const [field, checks] of Object.entries(rules)) {
const value = obj[field];
for (const check of checks) {
if (!check.test(value)) {
errors.push({ field, message: check.message });
}
}
}
return errors.length === 0 ? { valid: true } : { valid: false, errors };
}
function main() {
const orders = [
{ id: 1, customer: "Alice", product: "Book", amount: 25 },
{ id: 2, customer: "Bob", product: "Pen", amount: 5 },
{ id: 3, customer: "Alice", product: "Notebook", amount: 15 },
{ id: 4, customer: "Alice", product: "Book", amount: 25 },
{ id: 5, customer: "Bob", product: "Pencil", amount: 3 },
];
console.log("--- input ---");
console.log(orders);
console.log("\n--- prc ---");
const unique = prc(orders, (o) => o.customer + o.product);
console.log(unique);
console.log("\n--- tfm ---");
const grouped = tfm(orders, {
groupBy: (o) => o.customer,
transform: (o) => o.product,
getValue: (o) => o.amount,
});
console.log(grouped);
console.log("\n--- vld ---");
const newOrder = { id: 6, customer: "", product: "Eraser", amount: -2 };
const result = vld(newOrder, {
customer: [{ test: (v) => v && v.length > 0, message: "required" }],
amount: [{ test: (v) => v > 0, message: "must be positive" }],
});
console.log(result);
}
main();
export { prc, tfm, vld };