w3resource

JavaScript: Return the singular or plural form of the word based on the input number

JavaScript fundamental (ES6 Syntax): Exercise-164 with Solution

Write a JavaScript program that will return the singular or plural form of the word based on the input number.

If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s if the supplied dictionary contains the word.

  • Use a closure to define a function that pluralizes the given word based on the value of num.
  • If num is either -1 or 1, return the singular form of the word.
  • If num is any other number, return the plural form.
  • Omit the third argument, plural, to use the default of the singular word + s, or supply a custom pluralized word when necessary.
  • If the first argument is an object, return a function which can use the supplied dictionary to resolve the correct plural form of the word.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const pluralize = (val, word, plural = word + 's') => {
  const _pluralize = (num, word, plural = word + 's') =>
    [1, -1].includes(Number(num)) ? word : plural;
  if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
  return _pluralize(val, word, plural);
};
pluralize(0, 'apple'); // 'apples'
pluralize(1, 'apple'); // 'apple'
pluralize(2, 'apple'); // 'apples'
pluralize(2, 'person', 'people'); // 'people'

const PLURALS = {
  person: 'people',
  radius: 'radii'
};
const autoPluralize = pluralize(PLURALS);
console.log(autoPluralize(2, 'person')); // 'people'

Sample Output:

people

Flowchart:

flowchart: Return the singular or plural form of the word based on the input number

Live Demo:

See the Pen javascript-basic-exercise-163-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to convert a number in bytes to a human-readable string.
Next: Write a JavaScript program to perform left-to-right function composition.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes doesn't have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Ref: https://bit.ly/3fFFgZv