Use pluralize function for pluralization

This commit is contained in:
Koen Vlaswinkel
2023-06-19 16:37:56 +02:00
parent 768c10734e
commit 32d8968c56
3 changed files with 40 additions and 8 deletions

View File

@@ -7,8 +7,9 @@ export function pluralize(
numItems: number | undefined,
singular: string,
plural: string,
numberFormatter: (value: number) => string = (value) => value.toString(),
): string {
return numItems !== undefined
? `${numItems} ${numItems === 1 ? singular : plural}`
? `${numberFormatter(numItems)} ${numItems === 1 ? singular : plural}`
: "";
}

View File

@@ -3,6 +3,7 @@ import { useCallback, useMemo, useState } from "react";
import styled from "styled-components";
import { ExternalApiUsage } from "../../data-extensions-editor/external-api-usage";
import { ModeledMethod } from "../../data-extensions-editor/modeled-method";
import { pluralize } from "../../pure/word";
import { ModeledMethodDataGrid } from "./ModeledMethodDataGrid";
import { calculateModeledPercentage } from "./modeled";
import { decimalFormatter, percentFormatter } from "./formatters";
@@ -72,9 +73,14 @@ export const LibraryRow = ({
{isExpanded ? null : (
<>
{" "}
({decimalFormatter.format(externalApiUsages.length)} method
{externalApiUsages.length !== 1 ? "s" : ""},{" "}
{percentFormatter.format(modeledPercentage / 100)} modeled)
(
{pluralize(
externalApiUsages.length,
"method",
"methods",
decimalFormatter.format.bind(decimalFormatter),
)}
, {percentFormatter.format(modeledPercentage / 100)} modeled)
</>
)}
</TitleContainer>
@@ -82,12 +88,20 @@ export const LibraryRow = ({
<>
<StatusContainer>
<div>
{decimalFormatter.format(externalApiUsages.length)} method
{externalApiUsages.length !== 1 ? "s" : ""}
{pluralize(
externalApiUsages.length,
"method",
"methods",
decimalFormatter.format.bind(decimalFormatter),
)}
</div>
<div>
{decimalFormatter.format(usagesCount)} usage
{usagesCount !== 1 ? "s" : ""}
{pluralize(
usagesCount,
"usage",
"usages",
decimalFormatter.format.bind(decimalFormatter),
)}
</div>
<div>
{percentFormatter.format(modeledPercentage / 100)} modeled

View File

@@ -14,5 +14,22 @@ describe("word helpers", () => {
it("should return the empty string if the number is undefined", () => {
expect(pluralize(undefined, "thing", "things")).toBe("");
});
it("should return an unformatted number when no formatter is specified", () => {
expect(pluralize(1_000_000, "thing", "things")).toBe("1000000 things");
});
it("should return a formatted number when a formatter is specified", () => {
const formatter = new Intl.NumberFormat("en-US", {
style: "decimal",
});
expect(
pluralize(
1_000_000,
"thing",
"things",
formatter.format.bind(formatter),
),
).toBe("1,000,000 things");
});
});
});