Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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`));
Score Postcode
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment