From 3288d86e29dd5a0e73781f440f70c33f2b9e1608 Mon Sep 17 00:00:00 2001 From: Sumner Evans Date: Sat, 7 Dec 2024 18:31:48 -0700 Subject: [PATCH] web/util: fix oxfordHumanJoin(React)? for two-element arrays Signed-off-by: Sumner Evans --- web/src/util/join.ts | 11 +++++++++-- web/src/util/reactjoin.tsx | 17 ++++++++++++----- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/web/src/util/join.ts b/web/src/util/join.ts index 2252efb..af7500e 100644 --- a/web/src/util/join.ts +++ b/web/src/util/join.ts @@ -13,7 +13,12 @@ // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -export function humanJoin(arr: string[], sep: string = ", ", lastSep: string = " and "): string { +export function humanJoin( + arr: string[], + sep: string = ", ", + sep2: string = " and ", + lastSep: string = " and ", +): string { if (arr.length === 0) { return "" } @@ -21,7 +26,9 @@ export function humanJoin(arr: string[], sep: string = ", ", lastSep: string = " return arr[0] } if (arr.length === 2) { - return arr.join(lastSep) + return arr.join(sep2) } return arr.slice(0, -1).join(sep) + lastSep + arr[arr.length - 1] } + +export const oxfordHumanJoin = (arr: string[]) => humanJoin(arr, ", ", " and ", ", and ") diff --git a/web/src/util/reactjoin.tsx b/web/src/util/reactjoin.tsx index 96f450d..9997251 100644 --- a/web/src/util/reactjoin.tsx +++ b/web/src/util/reactjoin.tsx @@ -18,13 +18,20 @@ import { Fragment, JSX } from "react" export function humanJoinReact( arr: (string | JSX.Element)[], sep: string | JSX.Element = ", ", + sep2: string | JSX.Element = " and ", lastSep: string | JSX.Element = " and ", ): JSX.Element[] { - return arr.map((elem, idx) => - + return arr.map((elem, idx) => { + let separator = sep + if (idx === arr.length - 2) { + separator = (arr.length === 2) ? sep2 : lastSep + } + return {elem} - {idx < arr.length - 1 ? (idx === arr.length - 2 ? lastSep : sep) : null} - ) + {idx < arr.length - 1 ? separator : null} + + }) } -export const joinReact = (arr: (string | JSX.Element)[]) => humanJoinReact(arr, " ", " ") +export const oxfordHumanJoinReact = (arr: (string | JSX.Element)[]) => humanJoinReact(arr, ", ", " and ", ", and ") +export const joinReact = (arr: (string | JSX.Element)[]) => humanJoinReact(arr, " ", " ", " ")