-
Notifications
You must be signed in to change notification settings - Fork 0
/
cooky.ts
61 lines (44 loc) · 1.72 KB
/
cooky.ts
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
import {
DOMParser,
Element,
} from "https://deno.land/x/deno_dom/deno-dom-wasm.ts";
import { parse } from "https://deno.land/std@0.184.0/flags/mod.ts";
import { assert } from "https://deno.land/std@0.184.0/_util/asserts.ts";
const args = parse(Deno.args, { string: ["urls"] });
if (!args.urls) {
throw new Error("--urls is required");
}
const csvData = await Deno.readTextFile(args.urls);
const urls = csvData.split("\n");
const ingredients = new Map<string, Map<string, number>>();
for (const url of urls) {
const textResponse = await fetch(url);
const textData = await textResponse.text();
const document = new DOMParser().parseFromString(textData, "text/html");
assert(document);
[...document.querySelectorAll(".kptn-ingredient")].forEach((el) => {
if (!(el instanceof Element)) {
return;
}
const ingredient = el.textContent.trim();
const row = el.parentElement?.parentElement;
const amountElement = row?.querySelector(".kptn-ingredient-measure");
const amountTuple = amountElement?.textContent.trim() ?? "1 count";
const [rawAmount, rawMeasure] = amountTuple.split(" ");
const amount = parseFloat(rawAmount);
const measure = rawMeasure ?? 'count';
const previousAmounts = ingredients.get(ingredient) ?? new Map();
const previousAmount = previousAmounts?.get(measure) ?? 0;
previousAmounts.set(measure, previousAmount + amount);
ingredients.set(ingredient, previousAmounts);
});
}
const results: string[] = [];
ingredients.forEach((amounts, ingredient) => {
const entries: string[] = [];
amounts.forEach((value, unit) => {
entries.push(`${value} ${unit}`);
});
results.push([ingredient, ...entries].join('\t'));
});
console.log(results.join('\n'))