Because I despise nitpicking stuff like indentation and spacing in pull request comments, I'd like to nudge forward our automated style checking, at least for new files being added. I don't want to totally rewrite server.js just to get automated style checking… the blame tracking is just too useful. So let's it's just take care of that when we start splitting it out. More discussion in #948.
71 lines
1.6 KiB
JavaScript
71 lines
1.6 KiB
JavaScript
/**
|
|
* Commonly-used functions for formatting text in badge labels. Includes
|
|
* ordinal numbers, currency codes, star ratings, etc.
|
|
*/
|
|
'use strict';
|
|
|
|
function starRating(rating) {
|
|
let stars = '';
|
|
while (stars.length < rating) { stars += '★'; }
|
|
while (stars.length < 5) { stars += '☆'; }
|
|
return stars;
|
|
}
|
|
|
|
// Convert ISO 4217 code to unicode string.
|
|
function currencyFromCode(code) {
|
|
return ({
|
|
CNY: '¥',
|
|
EUR: '€',
|
|
GBP: '₤',
|
|
USD: '$',
|
|
})[code] || code;
|
|
}
|
|
|
|
function ordinalNumber(n) {
|
|
const s=['ᵗʰ','ˢᵗ','ⁿᵈ','ʳᵈ'], v=n%100;
|
|
return n+(s[(v-20)%10]||s[v]||s[0]);
|
|
}
|
|
|
|
// Given a number, string with appropriate unit in the metric system, SI.
|
|
// Note: numbers beyond the peta- cannot be represented as integers in JS.
|
|
const metricPrefix = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
|
|
const metricPower = metricPrefix
|
|
.map(function(a, i) { return Math.pow(1000, i + 1); });
|
|
function metric(n) {
|
|
for (let i = metricPrefix.length - 1; i >= 0; i--) {
|
|
const limit = metricPower[i];
|
|
if (n >= limit) {
|
|
n = Math.round(n / limit);
|
|
return ''+n + metricPrefix[i];
|
|
}
|
|
}
|
|
return ''+n;
|
|
}
|
|
|
|
// Remove the starting v in a string.
|
|
function omitv(version) {
|
|
if (version.charCodeAt(0) === 118) {
|
|
return version.slice(1);
|
|
}
|
|
return version;
|
|
}
|
|
|
|
function maybePluralize(singular, countable, plural) {
|
|
plural = plural || `${singular}s`;
|
|
|
|
if (countable && countable.length === 1) {
|
|
return singular;
|
|
} else {
|
|
return plural;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
starRating,
|
|
currencyFromCode,
|
|
ordinalNumber,
|
|
metric,
|
|
omitv,
|
|
maybePluralize
|
|
};
|