|
| 1 | +--- |
| 2 | +descriptions: ["deno"] |
| 3 | +--- |
| 4 | + |
| 5 | +### 2025 Solution Deno |
| 6 | + |
| 7 | +```Deno |
| 8 | +class LetterCounter { |
| 9 | + private counts: Map<string, number>; |
| 10 | +
|
| 11 | + constructor() { |
| 12 | + this.counts = new Map<string, number>(); |
| 13 | + } |
| 14 | +
|
| 15 | + public async processFile(filename: string): Promise<void> { |
| 16 | + const file = await Deno.open(filename); |
| 17 | + const buffer = new Uint8Array(1024); |
| 18 | +
|
| 19 | + let leftover = ""; |
| 20 | + let bytesRead: number | null; |
| 21 | +
|
| 22 | + while ((bytesRead = await file.read(buffer)) !== null) { |
| 23 | + const chunk = leftover + new TextDecoder().decode(buffer.subarray(0, bytesRead)); |
| 24 | + leftover = this.processChunk(chunk); |
| 25 | + } |
| 26 | + } |
| 27 | +
|
| 28 | + public printCounts(): void { |
| 29 | + const sortedCounts = Array.from(this.counts.entries()).sort(([aKey], [bKey]) => { |
| 30 | + return aKey.localeCompare(bKey, undefined, { numeric: true }); |
| 31 | + }); |
| 32 | +
|
| 33 | + for (const [letter, count] of sortedCounts) { |
| 34 | + console.log(`${letter}: ${count}`); |
| 35 | + } |
| 36 | + } |
| 37 | +
|
| 38 | + private processChunk(chunk: string): string { |
| 39 | + const letters = chunk.split(/\s+/); |
| 40 | + const leftover = letters.pop() || ""; |
| 41 | + for (const letter of letters) { |
| 42 | + this.addToCount(letter); |
| 43 | + } |
| 44 | + return leftover; |
| 45 | + } |
| 46 | + |
| 47 | + private addToCount(letter: string): void { |
| 48 | + const currentCount = this.counts.get(letter) || 0; |
| 49 | + this.counts.set(letter, currentCount + 1); |
| 50 | + } |
| 51 | +} |
| 52 | +
|
| 53 | +if (import.meta.main) { |
| 54 | + const file = "letters_challenge.txt" |
| 55 | +
|
| 56 | + const myLetterCounter = new LetterCounter(); |
| 57 | +
|
| 58 | + await myLetterCounter.processFile(file); |
| 59 | +
|
| 60 | + myLetterCounter.printCounts(); |
| 61 | +} |
| 62 | +
|
| 63 | +``` |
0 commit comments