@hackoregon/utils
Version:
Common utils for CIVIC
106 lines (84 loc) • 2.31 kB
JavaScript
import { format } from "d3-format";
import { timeFormat } from "d3-time-format";
import { startCase, toLower } from "lodash";
var scales = [[1000000000000, "trillion"], [1000000000, "billion"], [1000000, "million"]];
var abbreviateLarge = function abbreviateLarge(number) {
var num;
var scale;
for (var i = 0; i <= scales.length; i += 1) {
if (Math.abs(number) >= scales[i][0]) {
num = format(".2~r")(number / scales[i][0]);
scale = scales[i][1];
break;
}
}
return "".concat(num, " ").concat(scale);
};
var numeric = function numeric(d) {
var formatted;
if (Math.abs(d) >= 1000000) {
formatted = abbreviateLarge(d);
} else {
formatted = format(",.0f")(d);
}
return formatted;
};
var roundedDecimal = function roundedDecimal(d) {
return format(",.2f")(d);
};
var scalesShort = [[1000000000000, "t"], [1000000000, "b"], [1000000, "m"], [1000, "k"]];
var abbreviateLargeShort = function abbreviateLargeShort(number) {
var num;
var scale;
for (var i = 0; i <= scalesShort.length; i += 1) {
if (Math.abs(number) >= scalesShort[i][0]) {
num = format(".2~r")(number / scalesShort[i][0]);
scale = scalesShort[i][1];
break;
}
}
return "".concat(num).concat(scale);
};
var numericShort = function numericShort(d) {
var formatted;
if (Math.abs(d) >= 1000) {
formatted = abbreviateLargeShort(d);
} else {
formatted = format(",.0f")(d);
}
return formatted;
};
var decimalToPercent = function decimalToPercent(num) {
var formatted;
if (Number.isInteger(num)) {
formatted = format(",~%")(num);
} else {
formatted = format(",.1%")(num);
}
return formatted;
};
var year = format(".0f");
var percentage = format(".0%");
var dollars = function dollars(d) {
return "$".concat(numeric(d));
};
var titleCase = function titleCase(str) {
return startCase(toLower(str));
};
var unformatted = function unformatted(d) {
return d;
};
var monthYear = timeFormat("%B %Y");
var civicFormat = {
numeric: numeric,
roundedDecimal: roundedDecimal,
year: year,
percentage: percentage,
dollars: dollars,
titleCase: titleCase,
unformatted: unformatted,
monthYear: monthYear,
numericShort: numericShort,
decimalToPercent: decimalToPercent
};
export default civicFormat;