Skip to content

Instantly share code, notes, and snippets.

@renatoaraujoc
Last active May 22, 2024 17:10
Show Gist options
  • Save renatoaraujoc/bc933a315800b4f45e28898fae1c18ee to your computer and use it in GitHub Desktop.
Save renatoaraujoc/bc933a315800b4f45e28898fae1c18ee to your computer and use it in GitHub Desktop.
Typesafe Singular/Plural String Builder function
type SingularPluralSignature = {
length: number;
singular: string;
plural: string;
ifLengthZero?: string;
};
const buildSingularPluralString = (...args: Array<string | SingularPluralSignature>) =>
args.reduce((acc, next) =>
typeof next === 'string' ? [
...acc,
next
] : [
...acc,
...(next.length > 1 ? [
next.plural
] : [
next.length === 0 && next?.ifLengthZero ? next.ifLengthZero : next.singular
])
], [] as string[]).join('')
const numberDevs = 2;
const builtString = buildSingularPluralString('Oie, ', {
length: numberDevs,
ifLengthZero: 'não temos devs',
singular: 'eu sou um dev',
plural: `nós somos ${numberDevs} devs`
}, '!')
console.log(builtString);
@IgorHalfeld
Copy link

type SingularPluralSignature = {
  length: number;
  singular: string;
  plural: string;
};

const buildSingularPluralString = (
  ...args: Array<string | SingularPluralSignature>
) => {
  const words = args.reduce((acc, next) => {
    const isString = typeof next === "string";

    const phase: string[] = [...acc];

    if (isString) {
      phase.push(next);
    }

    const isPlural = next.length > 1;
    if (!isString && isPlural) {
      return [next.plural];
    }

    if (!isString && !isPlural) {
      return [next.singular];
    }

    return phase;
  }, [] as string[]);

  const phase = words.join("");
  return phase;
};

// Test
const numberDevs = 2;

const builtString = buildSingularPluralString(
  "Oie, ",
  {
    length: numberDevs,
    singular: "eu sou um dev",
    plural: `nós somos ${numberDevs} devs`,
  },
  "!",
);

console.log(builtString);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment