From 7d2295766634b9334ad9371334b076a9e0a1b1f5 Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 1 Dec 2023 20:57:47 -0500 Subject: [PATCH] simplify --- 2023/day_01/solution.ts | 18 +----------------- _utils/index.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/2023/day_01/solution.ts b/2023/day_01/solution.ts index e819d83..6cee9e8 100644 --- a/2023/day_01/solution.ts +++ b/2023/day_01/solution.ts @@ -25,7 +25,7 @@ In this example, the calibration values of these four lines are 12, 38, 15, and Consider your entire calibration document. What is the sum of all of the calibration values? */ -import { sum } from "../../_utils"; +import { sum, allIndicesOf } from "../../_utils"; const extractDigits = (s: string): string => s.replaceAll(/[a-zA-Z]/g, ""); const firstLast = (s: string): number => +`${s[0]}${s[s.length - 1]}`; @@ -70,22 +70,6 @@ const digits = [ "nine", ]; -const allIndicesOf = (s: string, search: string): number[] => { - let results = []; - let lastResult = -1; - while (lastResult <= s.length) { - const newResult = s.indexOf(search, lastResult + 1); - if (newResult == -1) { - break; - } else { - results.push(newResult); - lastResult = newResult; - } - } - - return results; -}; - type Match = { digitNum: number; startPos: number; diff --git a/_utils/index.ts b/_utils/index.ts index 62f6a6f..6a6f6d3 100644 --- a/_utils/index.ts +++ b/_utils/index.ts @@ -63,3 +63,21 @@ export function sum(a: number, b: number): number { export function emptyLines(line?: string): boolean { return !!line; } + +export function unique(arr: T[]): T[] { + return arr.reduce((res, current) => { + if (res.includes(current)) { + return res; + } else { + return [...res, current]; + } + }, []); +} + +export function allIndicesOf(s: string, search: string): number[] { + return unique( + s + .split("") + .reduce((results, _, index) => [...results, s.indexOf(search, index)], []) + ).filter((x: number) => x >= 0); +}