Problem overview
The method stutterize receives a word, word, with at least two letters. It returns the word said with a stutter: its first two characters, a hyphen, then the whole word.
"dog" becomes "do-dog". "Hello" becomes "He-Hello", because the characters keep their case. A two-letter word like "ab" gives "ab-ab": its first two characters are the whole word.
Approach
The result has three pieces: the start of the word, a fixed hyphen and the word itself. word.slice(0, 2) returns the characters from index 0 up to, but not including, index 2, so it returns the characters at indexes 0 and 1. Because the word has at least two letters, those two characters always exist. The three pieces are joined with +.
Step by step
- Slice the first two characters with
word.slice(0, 2). - Add the hyphen as the string
"-". - Add the whole word and return the joined string.
Where each piece comes from
For "dog", slice(0, 2) returns "do", the hyphen is the literal "-", and the last piece is "dog" itself. Joined in that order they give "do-dog". The two copies of the word are different strings: one is a slice, the other is the original, and word is not modified by the call.
The solution in JavaScript
class Solution {
stutterize(word) {
return word.slice(0, 2) + "-" + word;
}
}
On the examples it returns:
"dog" -> "do-dog"
"Hello" -> "He-Hello"
"ab" -> "ab-ab"
The method is named stutterize, so keep that name in the editor.
Another way to join
A template literal builds the same string: `${word.slice(0, 2)}-${word}` gives "do-dog" for "dog". The lesson uses +, which is enough for three pieces. A slice never throws when it asks for more than the string holds: "a".slice(0, 2) is "a", so a one-letter word would give "a-a". The lesson always has at least two letters.
Thinking about the problem
A stutter is a start followed by the complete word, so the result always contains the word unchanged at its end. That makes the second half trivial, and the only work is the start. Because the start is "the first two characters", one slice from index 0 with the end 2 is enough. Checking the three examples against the shape start, hyphen, word shows that each one fits: do, -, dog, and so on.
The hyphen is a one-character string, written between quotes like any other text.
If the result looks wrong, print the three pieces on separate lines. The hyphen is text, so it needs its quotes: "-".
Edge cases and common mistakes
- Ending the slice at 1.
slice(0, 1)keeps only one character. The end index is excluded, so two characters need an end of 2. - Using only the first two characters at the end. After the hyphen comes the whole word, not another slice.
- Changing the case. No conversion is needed:
"Hello"starts with a capitalHin both halves.
Testing
"To"gives"To-To"."hello"gives"he-hello".
Putting the pieces in the wrong order shows why the order matters: "dog" + "-" + "dog".slice(0, 2) gives "dog-do", which is not a stutter.
