Published
Edited
Nov 11, 2021
Insert cell
Insert cell
Insert cell
speakableQuantityString(new Qty('J^2/s^3'))
Insert cell
speakableQuantityString(new Qty('s'))
Insert cell
speakableQuantityString(new Qty('15 cs'))
Insert cell
speakableQuantityString(new Qty('14 TiB/ms'))
Insert cell
speakableQuantityString(new Qty('24 nS'))
Insert cell
speakableQuantityString(new Qty('24 VA/afurlong'))
Insert cell
speakableQuantityString(new Qty('24 degF'))
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// Takes an internal unit string representation from JS-quantities and makes it speakable.
speakableUnit = (unitString, singularize = false) => {
// Replace the angled brackets inserted by JS-Quantities
const rawUnitString = unitString.replaceAll(/[<>]/g, '');
// Get the unit string's unit prefix if existent (for example, 'nano')
const prefix = rawUnitString.match(prefixRegExp)?.[0] || '';
// Find the longest unit name string because we assume it's the most likely speakable variant
const longestUnit = Qty
.getAliases(rawUnitString.replace(prefixRegExp, ''))
.sort((a,b) => b.length - a.length)[0];

// Use prefix and longest name variant to build the final unit string, singularize if requested
return prefix + (singularize ? inflection.singularize(longestUnit) : longestUnit);
}
Insert cell
speakableUnitArray = (array, scalar, singularize) => {
if (array.length === 1) {
return speakableUnit(array[0], singularize);
}
if (_.uniq(array).length === 1) {
if (array.length === 3) {
return `${speakableUnit(array[0], singularize)} cubed`;
}
if (array.length === 2) {
return `${speakableUnit(array[0], singularize)} squared`;
}
return `${speakableUnit(array[0], singularize)} to the power of ${array.length}`;
}
return array.join(' by ');
}
Insert cell
speakableQuantityString = (q) => {
const f = (array, scalar, singularize) => speakableUnitArray(reducePrefixes(array), scalar, singularize);
const scalar = q.scalar === 1 ? '' : (q.scalar) || '';
if (q.denominator[0] !== "<1>") {
return `${scalar} ${f(q.numerator, scalar)} per ${f(q.denominator, undefined, true)}`.trim();
}
return `${scalar} ${f(q.numerator, scalar)}`.trim();
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more