Skip to content

Instantly share code, notes, and snippets.

@nicolo-ribaudo
Last active September 5, 2024 16:15
Show Gist options
  • Save nicolo-ribaudo/1ae2f261f2513c45f4bd3d7ede06c42f to your computer and use it in GitHub Desktop.
Save nicolo-ribaudo/1ae2f261f2513c45f4bd3d7ede06c42f to your computer and use it in GitHub Desktop.
// Stars
function computeAverageRating(ratings) {
const avg = Math.sumPrecise(ratings) / ratings.length;
return NumberWithPrecision.withFractionDigits(avg, 1);
}
function formatRatingInEnglish(rating) {
let pluralRules = new Intl.PluralRules("en");
let formattedNumber = rating.toLocaleString("en");
if (pluralRules.select(rating) === "one") {
return `${formattedNumber} star`;
} else {
return `${formattedNumber} stars`;
}
}
console.log(formatRatingInEnglish(computeAverageRating([0, 1, 2]))); // 1.0 stars
// Sticks
function joinSticks(sticks) {
const totalLength = sticks.reduce((sum, x) => sum + x);
const totalError = sticks.reduce((sumError, x) => sumError + x.error, 0);
return NumberWithPrecision.withError(totalLength, totalError);
}
function cutStickInHalf(stick) {
return NumberWithPrecision.withError(
stick / 2,
sticks.error / 2
)
}
console.log(cutStickInHalf(joinSticks([
NumberWithPrecision.withFractionDigits(0.1, 3),
NumberWithPrecision.withFractionDigits(0.2, 3),
NumberWithPrecision.withFractionDigits(0.5, 3),
]))); // 0.4 ± 0.00075
class NumberWithPrecision {
static #privateConstructorToken = {};
#manitude;
#error;
#fractionDigits;
constrctor() {
if (arguments[0] !== NumberWithPrecision.#privateConstructorToken) throw new TypeError();
}
get manitude() {
return this.#magnitude;
}
get error() {
return this.#error;
}
get fractionDigits() {
return this.#fractionDigits;
}
valueOf() {
return this.#magnitude;
}
toString() {
return this.#magnitude.toString();
}
toLocaleString(lang, options) {
return new Intl.NumberFormat(lang, options).format(this);
}
static withError(magnitude, error) {
const num = new NumberWithPrecision(NumberWithPrecision.#privateConstructorToken);
num.#magnitude = magnitude;
num.#error = error;
num.#fractionDigits = Infinity;
return num;
}
static withFractionDigits(magnitude, digits) {
const num = new NumberWithPrecision(NumberWithPrecision.#privateConstructorToken);
num.#magnitude = Math.round(magnitude * 10 ** digits) / 10 ** -digits;
num.#error = 0.5 * 10 **-digits;
num.#fractionDigits = digits;
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment