2020-03-18 14:04:49 +00:00
|
|
|
import { EvaluatedNode, mapTemporal } from './temporal'
|
2019-11-28 11:03:23 +00:00
|
|
|
import {
|
|
|
|
areUnitConvertible,
|
|
|
|
convertUnit,
|
|
|
|
simplifyUnitWithValue,
|
|
|
|
Unit
|
|
|
|
} from './units'
|
|
|
|
|
|
|
|
export function simplifyNodeUnit(node) {
|
2020-03-16 17:09:41 +00:00
|
|
|
if (!node.unit || node.nodeValue === false || node.nodeValue == null) {
|
2019-11-28 11:03:23 +00:00
|
|
|
return node
|
|
|
|
}
|
|
|
|
const [unit, nodeValue] = simplifyUnitWithValue(node.unit, node.nodeValue)
|
2020-03-16 17:09:41 +00:00
|
|
|
|
2019-11-28 11:03:23 +00:00
|
|
|
return {
|
|
|
|
...node,
|
|
|
|
unit,
|
|
|
|
nodeValue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
export const getNodeDefaultUnit = (node, cache) => {
|
|
|
|
if (
|
|
|
|
node.question &&
|
|
|
|
node.unit == null &&
|
|
|
|
node.defaultUnit == null &&
|
2019-12-16 11:19:41 +00:00
|
|
|
node.formule?.unit == null
|
2019-11-28 11:03:23 +00:00
|
|
|
) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
node.unit ||
|
|
|
|
cache._meta.defaultUnits.find(unit =>
|
|
|
|
areUnitConvertible(node.defaultUnit, unit)
|
|
|
|
) ||
|
|
|
|
node.defaultUnit
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-03-18 14:04:49 +00:00
|
|
|
export function convertNodeToUnit(to: Unit, node: EvaluatedNode<number>) {
|
2019-11-28 11:03:23 +00:00
|
|
|
return {
|
|
|
|
...node,
|
|
|
|
nodeValue: node.unit
|
|
|
|
? convertUnit(node.unit, to, node.nodeValue)
|
|
|
|
: node.nodeValue,
|
2020-02-27 18:53:27 +00:00
|
|
|
temporalValue:
|
|
|
|
node.temporalValue && node.unit
|
|
|
|
? mapTemporal(
|
|
|
|
value => convertUnit(node.unit, to, value),
|
|
|
|
node.temporalValue
|
|
|
|
)
|
|
|
|
: node.temporalValue,
|
2019-11-28 11:03:23 +00:00
|
|
|
unit: to
|
|
|
|
}
|
|
|
|
}
|