This commit is contained in:
alex 2023-12-01 20:57:47 -05:00
parent 04815f59c3
commit 7d22957666
2 changed files with 19 additions and 17 deletions

View File

@ -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? 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 extractDigits = (s: string): string => s.replaceAll(/[a-zA-Z]/g, "");
const firstLast = (s: string): number => +`${s[0]}${s[s.length - 1]}`; const firstLast = (s: string): number => +`${s[0]}${s[s.length - 1]}`;
@ -70,22 +70,6 @@ const digits = [
"nine", "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 = { type Match = {
digitNum: number; digitNum: number;
startPos: number; startPos: number;

View File

@ -63,3 +63,21 @@ export function sum(a: number, b: number): number {
export function emptyLines(line?: string): boolean { export function emptyLines(line?: string): boolean {
return !!line; return !!line;
} }
export function unique<T>(arr: T[]): T[] {
return arr.reduce<T[]>((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);
}