Skip to content

Instantly share code, notes, and snippets.

@cblanc
Created May 18, 2020 14:58

Revisions

  1. cblanc revised this gist May 18, 2020. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions top10.csv
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    Score, Postcode
    197,WV99 1ZZ
    196,WV99 1ZY
    196,WV99 1YZ
  2. cblanc created this gist May 18, 2020.
    33 changes: 33 additions & 0 deletions score_postcodes.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    import * as fs from "fs";
    import * as path from "path";
    import * as csv from "fast-csv";

    interface NumberScore {
    scores: number[];
    remainingString: string;
    }

    const extractNumbers = (input: string): NumberScore => {
    const results = input.match(/[0-9]+/g);
    const remainingString = input.replace(/[0-9]+/g, "");
    const scores = results.map((e) => parseInt(e, 10));
    return { remainingString, scores };
    };

    const letterScore = (l: string): number => l.toUpperCase().charCodeAt(0) - 64;
    const add = (prev: number, curr: number) => prev + curr;
    const computeScore = (input: string): number => {
    const { scores, remainingString } = extractNumbers(input);

    const letterScores = remainingString
    .split("")
    .filter((e) => e.match(/\w/gi))
    .map((e) => letterScore(e));
    return [...scores, ...letterScores].reduce(add);
    };

    fs.createReadStream(path.resolve(__dirname, "output.csv"))
    .pipe(csv.parse({ headers: false }))
    .on("error", (error) => console.error(error))
    .on("data", (row) => console.log(`${computeScore(row[0])},${row[0]}`))
    .on("end", (rowCount: number) => console.log(`Parsed ${rowCount} rows`));
    10 changes: 10 additions & 0 deletions top10.csv
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    197,WV99 1ZZ
    196,WV99 1ZY
    196,WV99 1YZ
    196,WV98 1ZZ
    196,SS99 9YY
    195,WV99 1ZX
    195,WV99 1YY
    195,WV99 1XZ
    195,WV98 1ZY
    195,WV98 1YZ