The challenge: “Write a program that given a phrase can count the occurrences of each word in that phrase.” My code needs to return an object that has one property for each word in the phrase, and each property’s value should contain the word count.
So, where do I start? Hmm.
Well, the first thing that comes to mind is that I need to chop up the phrase and get words separated by spaces. How do I do that? Let’s ask the internet!
Ah, here’s what I need: the split() method, which splits a string object into an array. For example:
Now, how do I split a string using not just spaces as separators, but also tabs or newline characters? I have a feeling I’ll need a regular expression…
Yup, I do. The special character
\s will match any white space character. Cool! And to account for multiple whitespace characters, I can just use
\s+ since the
+ character matches the preceding character (in this case, white space) if it occurs 1 or more times. So I should be able to do this:
Great, I have an array of words! That wasn’t so hard, since I have used regular expressions before. (It was many years ago, back when I dabbled in PHP, but it seems that programming is a bit like riding a bike; you never forget it completely.)
##Counting Words and Creating an Object
Next, I need to do things: 1) count the instances of each word, and 2) convert this array into a list of properties within an object. I think these two things will happen at the same time, and I think I need a loop to iterate through my array of words. Something like:
But that code is just an empty shell; I need to give it some guts! After thinking about it for a while, I decided to try this:
Let’s see if that works… Woohoo! It mostly works! The only problem is that it fails the last test; it doesn’t handle reserved words like
toString. Hmm. Tricky, tricky!
Thankfully, I learned a bit about object prototypes in yesterday’s blog post, so at least this isn’t completely foreign to me. Yesterday I learned that every object inherits certain properties and methods from an “ancestral” object prototype.
What I didn’t know, which I learned just now by looking at other people’s submissions on exercism.io, is that you can create objects without prototypes! It’s a bit like a magic trick:
And just like that, problem solved! Hurrah!
Well, I could do more tonight, but I really want to relax and spend some time with my family since it’s Mother’s Day. I’ve been feeling somewhat sad today, since this is the first Mother’s Day without my mom; she passed away last year. But I’m also celebrating her life and how much she influenced me. And I’m thinking about how I can make the most of what I’ve learned from her, and how I can live my life in a way that would make her proud.