Problem overview
The method addIfMissing receives a shopping list items, an array of strings, and a word item. It adds item at the end of the list only when the list does not have it yet, and it returns the list. When the word is already there, the list stays exactly as it is. The list may start empty, and the constraints say it has 0 to 9 words in lowercase letters.
The examples:
["milk", "eggs"]with"bread"gives["milk", "eggs", "bread"], because "bread" is new.["milk", "eggs"]with"milk"gives["milk", "eggs"], because "milk" is already there.[]with"apples"gives["apples"]. The empty list has nothing, so "apples" is new and becomes the only item.
Approach
This is a yes-or-no question followed by an action. The question is "does the list already have this word?", which the array method includes answers with true or false. The action is push, which adds an item at the end. We want the action only when the answer is no, so we put a ! in front of the question to turn it around.
No loop is needed. The method includes looks through the list for us, and an empty list is no special case: it simply answers false.
Step by step
- Write an
ifwhose condition is!items.includes(item). It is true when the word is missing. Write the closing brace right away, so the block is complete before you fill it. - Inside the
if, callpushonitemswithitem. This runs only for a new word, so the list never gets the same word twice. - After the
if, returnitems. When the word was already there, the array comes back as it was.
The solution in JavaScript
class Solution {
addIfMissing(items, item) {
if (!items.includes(item)) {
items.push(item);
}
return items;
}
}
Details worth knowing
The method name is includes. Arrays have no contains method. Matching is exact, so "Milk" and "milk" are different words, though the constraints here keep every word lowercase.
The push method changes the array in place, so the caller's own list also gets the new word. The return sits outside the if, so it runs in both cases: whether the word was added or not.
Testing
Running the method on the three examples prints:
[ 'milk', 'eggs', 'bread' ]
[ 'milk', 'eggs' ]
[ 'apples' ]
Edge cases and common mistakes
- Dropping the
!. Without it, the word is added only when it is already there, which is the opposite of the task, and an empty list stays empty. - Returning inside the if. If the
returnis inside the braces, the method returns nothing when the word was already present, and the tests seeundefined. - Using the result of push.
pushreturns the new length of the array, not the array. Writingreturn items.push(item)would return a number, such as 3. - Adding first, checking later. If you push and then test, the word is always found, and duplicates are never prevented.
