Search⌘ K

Solution Review: Make a Sentence

Explore how to use functional programming in JavaScript to create sentences with flexible word inputs. Learn to apply partial functions that fix conjunctions and reuse the resulting functions with different word sets, enhancing code reusability and clarity.

We'll cover the following...

Solution #

Javascript (babel-node)
const sentence = (conjunction, ...otherWords) => {
const commasJoiningWords = otherWords.slice(0,-1).join(", ");
const lastWord = otherWords.pop();
return `${commasJoiningWords} ${conjunction} ${lastWord}`;
}
const partialFnction = (func, conjunction) => {
return (...otherWords) => {
return func(conjunction, ...otherWords);
}
}
function test(conjunction, ...otherWords){
const partialSentence = partialFnction(sentence, conjunction);
const ans = partialSentence(...otherWords);
return ans
}
console.log(test("and", "apple", "mango", "peach"))
console.log(test("or" , "bike" , "car" , "train"))
console.log(test("but" , "fish" , "potatoes" , "spicy"))

Explanation #

In this challenge, you were given the implementation of the sentence function. Let’s understand it first.

Javascript (babel-node)
const sentence = (conjunction, ...otherWords) => {
const commasJoiningWords = otherWords.slice(0,-1).join(", ");
const lastWord = otherWords.pop();
return `${commasJoiningWords} ${conjunction} ${lastWord}`;
}

It takes two parameters: conjunction, the first word, and otherWords, all of the remaining words needed to create the sentence. We use the spread operator for ...