Files
flyer-crawler.projectium.com/utils/priceParser.ts

56 lines
1.7 KiB
TypeScript

export const parsePrice = (price: string): number => {
// Handles formats like "$3.99", "2 for $5", "$0.69"
const match = price.match(/\$?(\d+\.?\d*)/);
if (!match) return 0;
let numericPrice = parseFloat(match[1]);
const forMatch = price.match(/(\d+)\s+for/i);
if(forMatch){
const quantity = parseInt(forMatch[1], 10);
if(quantity > 0){
return numericPrice / quantity;
}
}
return numericPrice;
};
/**
* Parses a price string into an integer number of cents.
* Handles formats like "$10.99", "99¢", "250".
* @param price The price string to parse.
* @returns The price in cents, or null if unparsable.
*/
export const parsePriceToCents = (price: string): number | null => {
if (!price || typeof price !== 'string') return null;
const cleanedPrice = price.trim();
// Handle "X for Y" cases - these are not a single item price.
if (cleanedPrice.match(/\d+\s+for/i)) {
return null;
}
// Handle "99¢" format
const centsMatch = cleanedPrice.match(/(\d+\.?\d*)\s?¢/);
if (centsMatch && centsMatch[1]) {
return Math.round(parseFloat(centsMatch[1]));
}
// Handle "$10.99" or "10.99" format
const dollarsMatch = cleanedPrice.match(/\$?(\d+\.?\d*)/);
if (dollarsMatch && dollarsMatch[1]) {
const numericValue = parseFloat(dollarsMatch[1]);
// If the original string did not contain a decimal, and it's a whole number > 50,
// it's likely already in cents (e.g., "399" for "$3.99").
if (!cleanedPrice.includes('.') && numericValue > 50 && numericValue % 1 === 0) {
return numericValue;
}
return Math.round(numericValue * 100);
}
return null;
};