Challenge Overview
The first challenge in the Callbacks and Higher Order functions module is called pluralize, and the prompt is as follows:Create a functionThis challenge’s prompt is very straightforward and we won’t be using any higher order functions to solve it. While it may seem basic, it’s still an important starting point because we’ll be applying the process of deriving a solution to all of the remaining challenges as well. Let’s start by breaking down some of the language used in this prompt so we can see what clues it gives us in terms of how to write a function that solves it.pluralize
that takes an array of strings as input and returns a new array with an "s" added to the end of each string in the input array. For example, if the string "carrot" is in the input array, it should become the string "carrots" in the output array.
The body of thepluralize
function should employ a single for loop that pluralizes each string in the input array.
Example:
Input
array = ["dog", "cat", "tree frog"]
Output
map(array) === ["dogs", "cats", "tree frogs"]
Solution Walkthrough
First, we’ll define our input and output. It’s clear that the input is an array. The important part here is that our function “returns a new array”; we’re returning something that did not previously exist, so we’ll have to initialize it.The next key phrase is that this function is making a change to “each” string in the input array. Anytime we’re doing something to some or all of the elements in a collection, we’ll generally need some form of iteration to accomplish this.
Lastly, we see that before we can push each element of the input into our output array, we’ll need to add another string to it: 's'. This will involve string concatenation. We'll then add each concatenated string to our output array, and return it after we're done.
Putting this all together, here's the pseudocode for our function:
pluralize(inputArr):
initialize empty array outputArr
for each string of inputArr
    concatenate string with 's'
    push concatenated string into outputArr
return outputArr
Let's go through this pseudocode step by step, using the example array from CSX as our input.
Coding Demonstration
const pluralize = (inputArr) => {
const outputArr = [];
for (let i = 0; i < inputArr.length; i += 1) {
outputArr.push(`${inputArr[i]}s`);
}
return outputArr;
};
const animals = ['dog', 'cat', 'tree frog'];
console.log(pluralize(animals)); // -> ['dogs', 'cats', 'tree frogs']