Repository navigation
fix: use numeric prefixes in math filters - #1016
draarivpatel-ui wants to merge 1 commit into
Conversation
| return +toValue(value) || 0 | ||
| value = toValue(value) | ||
| if (typeof value === 'boolean') return Number(value) | ||
| const num = parseFloat(value) |
There was a problem hiding this comment.
parseFloat keeps the decimal part of a prefix, but Ruby Liquid does not. In Utils.to_number, a string is read as a decimal only when the whole string matches /\A-?\d+\.\d+\z/. Any other string goes through String#to_i, which keeps only the integer prefix. So a decimal prefix with a unit gives a different result here than in Ruby (Ruby Liquid 5.14.0 compared with this branch):
| template | Ruby | this PR |
|---|---|---|
{{ "3.5px" | plus: 0 }} |
3 | 3.5 |
{{ "3.5px" | times: 2 }} |
6 | 7 |
{{ "4.2kg" | ceil }} |
4 | 5 |
{{ "2.5 apples" | round }} |
2 | 3 |
{{ "7.5x" | modulo: 2 }} |
1 | 1.5 |
The new tests only use integer prefixes (3 items, 10px, 16px), so they pass either way.
A version that keeps plain numeric strings as they are now ("1.5", ".5", "1e3"), and uses the integer prefix like to_i for everything else:
export function toNumber (value: any): number {
value = toValue(value)
if (typeof value === 'string' && !/^\s*[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?\s*$/i.test(value)) {
const prefix = /^\s*[+-]?\d+/.exec(value)
return prefix ? Number(prefix[0]) : 0
}
return +value || 0
}With this, all 5 rows above match Ruby. The new tests still pass: "3 items" | minus: 1 gives 2, "10px" | plus: 5 gives 15, "0x10" | plus: 0 gives 0 and "16px" | times: 2 gives 32. true | plus: 1 is still 2. One side effect: "Infinity" now gives 0 (Ruby gives 0 too; master gives Infinity).
Summary
10pxplus,minus,times, and non-decimal numeric prefixesThe other compatibility gaps in the report are already fixed on current master; this covers the remaining math conversion difference.
Fixes #995
Test plan
npx jest test/integration/filters/math.spec.ts src/util/underscore.spec.ts --runInBandnpm run lint