Estoy tratando de mostrar un mensaje basado en la actividad del usuario, el mensaje cambia según la cantidad de usuarios que regresaron en la carga others . El siguiente código funciona, pero es voluminoso y se siente mal de alguna manera.
Que estoy haciendo:
Menos de 3: “Junto con Billy Bob y Tom Thomason”.
Exactamente 3: “Junto con Billy Bob, Tom Thomason y Mary Maryland”.
Mayor que 3: “Junto con Billy Bob, Tom Thomason y otros 3”.
const handleActivitySummary = useCallback( (verb, others) => { if (verb === "SHARED_POST") { return "shared a post"; } else { const userJoined = verb === "MEMBER_ADDED"; let summary; userJoined ? (summary = `has joined ${post.slug}`) : (summary = `has left ${post.slug}`); if (others && others.length < 3) { summary += ` along with ${others .map((user) => user.full_name) .join(", ") .replace(/, ([^,]*)$/, " and $1")}`; } if (others && others.length === 3) { summary += ` along with ${others .map((user) => user.full_name) .join(", ") .replace(/, ([^,]*)$/, ", and $1")}`; } if (others && others.length > 3) { const newArray = others.slice(0, 3); const usersLeft = others.length - newArray.length; summary += ` along with ${newArray .map((user) => user.full_name) .join(", ")} and ${usersLeft} ${pluralize(usersLeft, "other")}`; } return summary; } }, [post] );Puede intentar resolver esto escribiendo un método de ayuda de Javascript personalizado como se muestra a continuación
"use strict"; const getSummary = (memberNames) => { const memberCount = memberNames.length; const statement = `along with `.concat(memberNames.slice(0, 3).join(", ")); if (memberCount > 0 && memberCount <= 3) { return statement.replace(/, ([^,]*)$/, " and $1"); } if (memberCount > 3) { return statement.replace(/, ([^,]*)$/, "").concat(` and ${memberCount - 2} others`); } return ""; }; console.log(getSummary([])); console.log(getSummary(["Alice"])); console.log(getSummary(["Alice", "Bob"])); console.log(getSummary(["Alice", "Bob", "Cameron"])); console.log(getSummary(["Alice", "Bob", "Cameron", "Dion"]));