Skip to content

Commit

Permalink
refactor: better price string parsing with regex
Browse files Browse the repository at this point in the history
  • Loading branch information
Ynng committed Mar 16, 2021
1 parent 14e3236 commit fc3c32f
Showing 1 changed file with 10 additions and 16 deletions.
26 changes: 10 additions & 16 deletions src/store/includes-labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,6 @@ export function includesLabels(
);
}

function getPriceFromString(priceString: string, euroFormat: boolean): number {
return Number.parseFloat(
priceString
.replace(/\\/g, '')
.replace(euroFormat ? /\./g : /,/g, '')
.match(/\d+/g)!
.join('.')
);
}

export async function getPrice(
page: Page,
query: Pricing,
Expand All @@ -135,12 +125,16 @@ export async function getPrice(
const priceString = await extractPageContents(page, selector);

if (priceString) {
const euroFormat = priceString.indexOf('.') < priceString.indexOf(',');
let price = getPriceFromString(priceString, euroFormat);
//Sanity check, flip "euroFormat" if price lower than 50
if (price < 50) {
price = Math.max(price, getPriceFromString(priceString, !euroFormat));
}
const thousandsSeparator =
priceString.search(/\d+\.\d{3}|\d+,\d{2}$/) > -1 ? /\./g : /,/g;
const price = Number.parseFloat(
priceString
.replace(/\\/g, '')
.replace(thousandsSeparator, '')
.match(/\d+/g)!
.join('.')
);

logger.debug('received price', price);
return price;
}
Expand Down

0 comments on commit fc3c32f

Please sign in to comment.