Files
omni-tools/src/pages/number/sum/service.ts

29 lines
797 B
TypeScript
Raw Normal View History

2024-06-25 03:11:48 +01:00
export type NumberExtractionType = 'smart' | 'delimiter';
function getAllNumbers(text: string): number[] {
const regex = /\d+/g;
const matches = text.match(regex);
return matches ? matches.map(Number) : [];
}
export const compute = (
input: string,
extractionType: NumberExtractionType,
printRunningSum: boolean,
separator: string
2024-06-25 03:13:24 +01:00
): string => {
2024-06-25 03:11:48 +01:00
let numbers: number[] = [];
if (extractionType === 'smart') {
numbers = getAllNumbers(input);
} else {
const parts = input.split(separator);
// Filter out and convert parts that are numbers
numbers = parts
.filter((part) => !isNaN(Number(part)) && part.trim() !== '')
.map(Number);
}
2024-06-25 03:13:24 +01:00
return numbers
.reduce((previousValue, currentValue) => previousValue + currentValue, 0)
.toString();
2024-06-25 03:11:48 +01:00
};