1
0
Fork 0

support fractions and comma decimal separators

This commit is contained in:
Enoch Riese 2023-07-26 16:38:51 -06:00
parent 7a48cafe22
commit 8781e60350
8 changed files with 309 additions and 140 deletions

View file

@ -151,39 +151,60 @@ export const getCrumbs = (app, slug = false) => {
/** convert a millimeter value to a Number value in the given units */
export const measurementAsUnits = (mmValue, units = 'metric') =>
mmValue / (units === 'imperial' ? 25.4 : 10)
round(mmValue / (units === 'imperial' ? 25.4 : 10), 3)
/** convert a value that may contain a fraction to a decimal */
export const fractionToDecimal = (value) => {
// if it's just a number, return it
if (!isNaN(value)) return value
// keep a running total
let total = 0
// split by spaces
let chunks = String(value).split(' ')
if (chunks.length > 2) return Number.NaN // too many spaces to parse
// a whole number with a fraction
if (chunks.length === 2) {
// shift the whole number from the array
const whole = Number(chunks.shift())
// if it's not a number, return NaN
if (isNaN(whole)) return Number.NaN
// otherwise add it to the total
total += whole
}
// now we have only one chunk to parse
let fraction = chunks[0]
// split it to get numerator and denominator
let fChunks = fraction.trim().split('/')
// not really a fraction. return NaN
if (fChunks.length !== 2 || fChunks[1] === '') return Number.NaN
// do the division
let num = Number(fChunks[0])
let denom = Number(fChunks[1])
if (isNaN(num) || isNaN(denom)) return NaN
return total + num / denom
}
export const measurementAsMm = (value, units = 'metric') => {
if (typeof value === 'number') return value * (units === 'imperial' ? 25.4 : 10)
if (value.endsWith('.')) return false
if (String(value).endsWith('.')) return false
if (units === 'metric') {
value = Number(value)
if (isNaN(value)) return false
return value * 10
} else {
const imperialFractionToMm = (value) => {
let chunks = value.trim().split('/')
if (chunks.length !== 2 || chunks[1] === '') return false
let num = Number(chunks[0])
let denom = Number(chunks[1])
if (isNaN(num) || isNaN(denom)) return false
else return (num * 25.4) / denom
}
let chunks = value.split(' ')
if (chunks.length === 1) {
let val = chunks[0]
if (!isNaN(Number(val))) return Number(val) * 25.4
else return imperialFractionToMm(val)
} else if (chunks.length === 2) {
let inches = Number(chunks[0])
if (isNaN(inches)) return false
let fraction = imperialFractionToMm(chunks[1])
if (fraction === false) return false
return inches * 25.4 + fraction
}
const decimal = fractionToDecimal(value)
if (isNaN(decimal)) return false
return decimal * 24.5
}
return false
}