-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_test_v2.js
More file actions
51 lines (41 loc) · 1.5 KB
/
Copy pathparse_test_v2.js
File metadata and controls
51 lines (41 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const parsePrice = str => {
if (!str) return 0;
// Replace terminal dashes with .00 (e.g. 12.- -> 12.00)
let clean = str.replace(/[.–\-]\s*$/g, '.00');
// Remove spaces and apostrophes (always grouping separators) and extract valid chars
clean = clean.replace(/[^\d,.]/g, '').replace(/['’\s]/g, '');
const lastComma = clean.lastIndexOf(',');
const lastDot = clean.lastIndexOf('.');
const lastSeparator = Math.max(lastComma, lastDot);
if (lastSeparator === -1) {
return parseFloat(clean) || 0;
}
const digitsAfterSeparator = clean.length - lastSeparator - 1;
if (digitsAfterSeparator === 3) {
// It's a grouping separator (e.g., 1,385 or 1.385.900)
clean = clean.replace(/[.,]/g, '');
} else {
// It's a decimal separator. Remove all separators before it, replace the last one with '.'
const before = clean.substring(0, lastSeparator).replace(/[.,]/g, '');
const after = clean.substring(lastSeparator + 1);
clean = before + '.' + after;
}
return parseFloat(clean) || 0;
};
const tests = [
["1.385.90", 1385.90],
["1,385.90", 1385.90],
["1.385,90", 1385.90],
["1,385,900", 1385900],
["1.385.900", 1385900],
["1,385", 1385],
["1.385", 1385],
["1'385.90", 1385.90],
["CHF 1'433.00", 1433],
["12.-", 12],
["Gratis", 0]
];
tests.forEach(([input, expected]) => {
const parsed = parsePrice(input);
console.log(`Input: ${input.padEnd(15)} | Parsed: ${parsed} | Expected: ${expected} | ${parsed === expected ? 'PASS' : 'FAIL'}`);
});