In the previous chapter, we started a project of creating a Naive Bayes Classifier (or NBC, for short). We’ve made improvements, but nothing so far really got to the heart of refactoring our functions and objects.

That’s what this chapter is all about.

Is Object-Oriented Programming Still Relevant in JavaScript?

In this and the next two chapters, we’re working with OOP. In some JavaScript styles, OOP is deemphasized in favor of functional programming. But beyond the practical reason of understanding OOP in JavaScript to support legacy projects, JavaScript’s OOP capabilities are still being expanded through the TC39 committee that decides on features for JavaScript.

It’s reasonable to have a personal preference for your own coding, but if your goal is to understand modern JavaScript, as of this writing, both FP and OOP are still being actively developed. With no clear “winner” at this point, it makes sense to learn about both.

The Code (Improved)

In case you skimmed over the last chapter or missed a step somewhere, here is the version we ended up with:

function fileName(){
  var theError = new Error("here I am");
  return theError.stack.match(/\/(\w+\.js)\:/)[1];
};
console.log(`Welcome to ${fileName()}!`);
var easy = 'easy';
var medium = 'medium';
var hard = 'hard';

imagine = ['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'];
somewhereOverTheRainbow = ['c', 'em', 'f', 'g', 'am'];
tooManyCooks = ['c', 'g', 'f'];
iWillFollowYouIntoTheDark = ['f', 'dm', 'bb', 'c', 'a', 'bbm'];
babyOneMoreTime = ['cm', 'g', 'bb', 'eb', 'fm', 'ab'];
creep = ['g', 'gsus4', 'b', 'bsus4', 'c', 'cmsus4', 'cm6'];
paperBag = ['bm7', 'e', 'c', 'g', 'b7', 'f', 'em', 'a', 'cmaj7',
            'em7', 'a7', 'f7', 'b'];
toxic = ['cm', 'eb', 'g', 'cdim', 'eb7', 'd7', 'db7', 'ab', 'gmaj7',
         'g7'];
bulletproof = ['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'];

var songs = [];
var labels = [];
var allChords = [];
var labelCounts = [];
var labelProbabilities = [];
var chordCountsInLabels = {};
var probabilityOfChordsInLabels = {};

function train(chords, label){
  songs.push([label, chords]);
  labels.push(label);
  chords.forEach(chord => {
    if(!allChords.includes(chord)){
      allChords.push(chord);
    }
  });
  if(Object.keys(labelCounts).includes(label)){
    labelCounts[label] = labelCounts[label] + 1;
  } else {
    labelCounts[label] = 1;
  }
};

function setLabelProbabilities(){
  Object.keys(labelCounts).forEach(function(label){
    labelProbabilities[label] = labelCounts[label] / songs.length;
  });
};

function setChordCountsInLabels(){
  songs.forEach(function(song){
    if(chordCountsInLabels[song[0]] === undefined){
      chordCountsInLabels[song[0]] = {};
    }
    song[1].forEach(function(chord){
      if(chordCountsInLabels[song[0]][chord] > 0){
        chordCountsInLabels[song[0]][chord] += 1;
      } else {
        chordCountsInLabels[song[0]][chord] = 1;
      }
    });
  });
}

function setProbabilityOfChordsInLabels(){
  probabilityOfChordsInLabels = chordCountsInLabels;
  Object.keys(probabilityOfChordsInLabels).forEach(
function(difficulty){
    Object.keys(probabilityOfChordsInLabels[difficulty]).forEach(
function(chord){
      probabilityOfChordsInLabels[difficulty][chord] /= songs.length;
    });
  });
}

train(imagine, easy);
train(somewhereOverTheRainbow, easy);
train(tooManyCooks, easy);
train(iWillFollowYouIntoTheDark, medium);
train(babyOneMoreTime, medium);
train(creep, medium);
train(paperBag, hard);
train(toxic, hard);
train(bulletproof, hard);

setLabelProbabilities();
setChordCountsInLabels();
setProbabilityOfChordsInLabels();

function classify(chords){
  var smoothing = 1.01;
  console.log(labelProbabilities);
  var classified = {};
  Object.keys(labelProbabilities).forEach(function(difficulty){
    var first = labelProbabilities[difficulty] + smoothing;
    chords.forEach(function(chord){
      var probabilityOfChordInLabel =
probabilityOfChordsInLabels[difficulty][chord];
      if(probabilityOfChordInLabel){
        first = first * (probabilityOfChordInLabel + smoothing);
      }
    });
    classified[difficulty] = first;
  });
  console.log(classified);
};

classify(['d', 'g', 'e', 'dm']);
classify(['f#m7', 'a', 'dadd9', 'dmaj7', 'bm', 'bm7', 'd', 'f#m']);

As was the case before, save this to a file called nb.js , and you can run it with this command:

node nb.js

We won’t have tests in place for another couple of sections. We’re still limping along by checking that our output hasn’t changed. You should get the following:

Welcome to nb.js!
[ easy: 0.3333333333333333,
  medium: 0.3333333333333333,
  hard: 0.3333333333333333 ]
{ easy: 2.023094827160494,
  medium: 1.855758613168724,
  hard: 1.855758613168724 }
[ easy: 0.3333333333333333,
  medium: 0.3333333333333333,
  hard: 0.3333333333333333 ]
{ easy: 1.3433333333333333,
  medium: 1.5060259259259259,
  hard: 1.6884223991769547 }

Array and Object Alternatives

Containers (especially arrays and objects) and iterating through them are fundamental concepts in programming JavaScript. In this section, we’ll explore more nuanced options JavaScript has available. Here are the topics that we’ll cover:

  • Array alternative: sets
  • Array alternative: objects
  • Object alternative: maps
  • Array alternative: bit fields

Array Alternative: Sets

A set is like an array, but can hold only one of a certain value (e.g., [1, 2, 3] , but not [1, 1, 2, 2, 3, 3] ). Although sets are iterable, like arrays, their interface is very different. Because they can only hold one of something, we can just try adding elements to them without checking if they are already there.

So with a set instead of an array, we can turn this code:

var allChords = []; //this is outside the train function

// this is inside the train function
chords.forEach(chord => {
  if(!allChords.includes(chord)){
    allChords.push(chord);
  }
});

into this code:

var allChords = new Set(); // this is outside the train function

// this is inside the train function
chords.forEach(chord => allChords.add(chord));

It saves four lines and a conditional check. Win-win. Make that change now.

Sets and maps don’t have all the handy array functions

For instance, as of this writing, neither Set nor Map has a map function. This would be nice, but there are some theoretical reasons that are out of scope here (having to do with the laws of functors , which we’ll discuss very briefly in Chapter 11 ) for why you’re stuck without native implementations. So, as far as convenient options go, you’re stuck with either converting to an array and back, or using forEach .

Array Alternative: Objects

Another possible alternative to an array is just an object.  This is especially the case if you have data where you:

  • Don’t care about the order
  • Want to mix types in the same structure
  • Want meaningful labels rather than numerical indices

Our code actually has a case like this already. Even though we initialized labelCounts and labelProbabilities as arrays, we’ve been using them as objects all along. To be more specific, we should change these lines:

var labelCounts = [];
var labelProbabilities = [];

to these:

var labelCounts = {};
var labelProbabilities = {};

Save/run/check/commit, and we’re still fine. The change to labelProbabilities does change half of the output somewhat ( {} instead of [] ), but this is actually more correct. One could argue that we’re now changing behavior and going beyond the scope of refactoring by making these changes. On the other hand, our output is only for visual inspection at this point. It still looks correct and, if anything, is improved a bit.

Arrays are not entirely distinct from objects

How did we get away with using an array instead of an object? Unfortunately, JavaScript allows you to declare an array and assign elements to string-based keys, as if it is an object.

We have two arrays left, songs and labels . If we look at how they’re used, they both have elements pushed to them, and songs is iterated through and has its length referenced. They are both justifiably arrays, but there are two points of interest here. First, labels is only “used” in the sense that elements are pushed onto it, but it isn’t actually referenced otherwise. It’s dead code, so these lines can be removed:

var labels = []; // near the top
labels.push(label); // inside the train function

(Save/run/check/commit.)

The second point to notice about songs is that “arrays” are pushed onto it, but these “arrays” just have two elements, neither of which is the same type. One is a label (a difficulty classification like “easy”), and one is an array of chords. This sounds like a better fit for an object than an array. To be clear, songs remains an array, but the things pushed onto it should be objects. This involves a few changes.

Inside the train function, what we push will be different:

// get rid of this line
songs.push([label, chords]);

// and replace it with this
songs.push({label: label, chords: chords});

Now we’re using an object instead of an array. This will break a lot of things. Before we fix that, though, we can make one minor change using the object property shorthand :

songs.push({label, chords});

Fortunately, since we haven’t changed songs itself, the calls from it ( length and forEach ) will still work fine. Inside the anonymous function for forEach   (inside of setChordCountsInLabels ), however, our references to song now have some problems .

Specifically, every reference to either song[0] or song[1] must be changed, respectively, to song.label and song.chords . You could just search and replace, but here’s another view on how to change the file:

-    if(chordCountsInLabels[song[0]] === undefined){
-      chordCountsInLabels[song[0]] = {}
+    if(chordCountsInLabels[song.label] === undefined){
+      chordCountsInLabels[song.label] = {}
     }
-    song[1].forEach(function(chord){
-      if(chordCountsInLabels[song[0]][chord] > 0){
-        chordCountsInLabels[song[0]][chord] += 1;
+    song.chords.forEach(function(chord){
+      if(chordCountsInLabels[song.label][chord] > 0){
+        chordCountsInLabels[song.label][chord] += 1;
       } else {
-        chordCountsInLabels[song[0]][chord] = 1;
+        chordCountsInLabels[song.label][chord] = 1;

We haven’t used this before, but this is how git diff represents changes. If you use Git, you’ll see this frequently. Every line with a - is a line to be deleted and replaced with the following line prepended with a + . Lines with no plus or minus are just provided for context.

At this point, you should be able to save, run the code, and verify the output has not changed.

Object Alternative: Maps

Now it seems that all of our arrays are proper arrays, instead of sets or objects in disguise. But what about those objects? Do we really want objects?

If you haven’t heard of Map (the object, not the function), you might be wondering what the alternative to an object would be. But after reading the last sentence, you might be guessing that it’s a map.

Why would you use a map over an object? (We’ll refer to both as “containers.”)

  • You want to easily know the size of the container.
  • You don’t want the hierarchical baggage that can come with objects.
  • You want a container for elements that are similar to one another.
  • You generally want to iterate through the container.

In most object-oriented languages, there is a map-like container available. Sometimes it’s called a dictionary or a hash , responsible for keys and values . And this is usually contrasted by a more heavyweight class system (with classes, instances, inheritance, etc.) that is intended to store state (attributes) and behavior (functions/methods).

In JavaScript, objects have traditionally filled both these roles, but the (yes, “pseudo” according to some) class system, along with modules, is taking over the larger architectural duties, whereas maps are intended to fulfill the more lightweight “keys and values” role.

In practical terms, this means that if most of your interactions with objects consist of looping through them, and they tend to store values of the same type (or at least values that can be used in the same way—e.g., addressed with similar functions), you probably want a map.

What does all that mean for us and our objects inside of our NBC?

They should all be maps.

Counterpoint: Maps are terrible...but just for now?

While our program’s data strongly suggests we should use maps instead of objects, there are also reasons we might want to avoid them:

  • The .get and .set notation is not as convenient as the object.property.property.etc syntax for dealing with deeply nested structures.
  • The API (in comparison to that of objects) may be unfamiliar to you or other members of your team
  • JSON stands for “JavaScript Object Notation.” When you get JSON data (from a remote API, for instance), it may simply be easier to work with it as an object. Converting objects to maps might not be worth the trouble.
  • Internal (native) and external (library) support is not as convenient for maps as it is for other containers (e.g., as of this writing Map has no map function).

For those reasons (especially the first one), we will end up leaving some the internal objects as they are, but still use maps for the outer containers.

The easiest object to convert to a map is the classified object inside the classify function, because it has the fewest lines. Here is the diff:

-  var classified = {};
+  var classified = new Map();
-  classified[difficulty] = first;
+  classified.set(difficulty, first);

When we save and run this, the output looks slightly different, but the numbers are all the same. Commit.

Next up, let’s see what it would take to  convert labelCounts from an object to a map:

-var labelCounts = {};
+var labelCounts = new Map();

-  if(Object.keys(labelCounts).includes(label)){
-    labelCounts[label] = labelCounts[label] + 1;
+  if(Array.from(labelCounts.keys()).includes(label)){
+    labelCounts.set(label, labelCounts.get(label) + 1);

-    labelCounts[label] = 1;
+    labelCounts.set(label, 1);

-  Object.keys(labelCounts).forEach(function(label){
-    labelProbabilities[label] = labelCounts[label] / songs.length;
+  labelCounts.forEach(function(_count, label){
+    labelProbabilities[label] = labelCounts.get(label) / songs.length;

Recall our git diff notation, where + is an added line and - is a deleted one.

The first change obviously just uses a Map constructor instead of assigning an empty object literal, {} . The second change is the most convoluted. In this, the meaning of the entire first line is to see if the label has not already been included.

In order to get the array of labels with our old object, we use the Object.keys function, which the labelCounts object as a parameter. To get the same array from our map, we have to first get an iterator with labelCounts.keys() . Unlike an array, this iterator object does not have an includes function, so we convert from an iterator to an array via the Array.from function.

Another somewhat confusing part is in change 4, where we forEach our way through the map. The odd part is that our anonymous function is using two parameters instead of one: _count and label .

The label is the key of our map, and the value is the _count . The underscore is there to signify that, although we must include something in the first spot of the parameter list in order to label and access the second one; the first is unused. Some would use just an _ , but there is no good reason not to name the variable something useful. Should someone later using this need to look up the function definition to realize what the first parameter means, or use console.log to find its value? Also, if the first parameter does turn out to be useful, it’s convenient to  just delete the underscore that prepends a perfectly useful and descriptive variable name.

Why did they do that?

The ordering of the parameters in the forEach function of Map is backward in that people usually describe hashes/dictionaries as “key/value pairs,” and here the value is listed first.

It might be nicer if it were (key, value) , rather than (value, key) , but I suppose the assumption is that people will more often be interested in strictly the value , meaning they would tend to call it with one parameter: (value) .

In any case, stay safe out there.

The other changes just reflect differences in getting attributes, .get( _thing_ ) versus [ _thing_ ] , and in setting attributes, .set( _thing, newValue_ ) versus [ _thing_ ] = _newValue_ . 

Through the same approach, you can convert labelProbabilities to a map as well.  Make the following changes:

- var labelProbabilities = {};
+ var labelProbabilities = new Map();

- labelProbabilities[label] = labelCounts.get(label) / songs.length;
+ labelProbabilities.set(label, labelCounts.get(label) / songs.length);

- Object.keys(labelProbabilities).forEach(function(difficulty){
-   var first = labelProbabilities[difficulty] + smoothing;
+ labelProbabilities.forEach(function(_probabilities, difficulty){
+   var first = labelProbabilities.get(difficulty) + smoothing;

At this point, you should still have code that runs and gives you the numbers you expect.

The other top-level objects ( chordCountsInLabels and probabilityOfChordsInLabels ) are a bit trickier to convert into maps. This is mostly because their state is global and mutable. They are also a bit more resistant to change because the latter is initially assigned to the former.

We can apply the same approach as before, although it’s more finicky this time. We will need the following changes:

-var chordCountsInLabels = {};
-var probabilityOfChordsInLabels = {};
+var chordCountsInLabels = new Map();
+var probabilityOfChordsInLabels = new Map();

-if(chordCountsInLabels[song.label] === undefined){
-  chordCountsInLabels[song.label] = {};
+if(chordCountsInLabels.get(song.label) === undefined){
+  chordCountsInLabels.set(song.label, {});

-if(chordCountsInLabels[song.label][chord] > 0){
-  chordCountsInLabels[song.label][chord] += 1;
+if(chordCountsInLabels.get(song.label)[chord] > 0){
+  chordCountsInLabels.get(song.label)[chord] += 1;

-chordCountsInLabels[song.label][chord] = 1;
+chordCountsInLabels.get(song.label)[chord] = 1;

-  Object.keys(probabilityOfChordsInLabels).forEach(
-function(difficulty){
-  Object.keys(probabilityOfChordsInLabels[difficulty]).forEach(
-    probabilityOfChordsInLabels[difficulty][chord] /= songs.length;
+probabilityOfChordsInLabels.forEach(function(_chords, difficulty){
+ Object.keys(probabilityOfChordsInLabels.get(difficulty)).forEach(
+  probabilityOfChordsInLabels.get(difficulty)[chord] /= songs.length;

-var probabilityOfChordInLabel = 
-probabilityOfChordsInLabels[difficulty][chord];
+var probabilityOfChordInLabel = 
+probabilityOfChordsInLabels.get(difficulty)[chord];

Save/run/check/commit.

“Weak” Versions of Set and Map

Before we leave our discussion of sets and maps, you should note that there are also WeakSet and WeakMap . The main differences between them and their “strong” (normal strength?) counterparts are:

  • They cannot be iterated (no forEach function).
  • They do not have a reference to their size.
  • WeakSet cannot store primitives.
  • They hold their keys “weakly”; that is, the keys are available for garbage collection when they don’t have any references.

Basically, with the weak forms, you give up the capability of easily knowing what is inside or applying functions to the whole set. And what you gain is control over memory leaks and privacy.

Array Alternative: Bit Fields

One more candidate for replacing arrays deserves a mention: bit fields. If you have an array that stores booleans, you might want bit fields in some cases. There is no native implementation of bit fields in JavaScript. However, you have access to numbers and bit-wise arithmetic, and that’s all you need.

Imagine you had the following conditionals:

states = [true,
          true,
          true,
          true,
          true,
          true,
          false,
          true]

You could also represent these in binary as 0b11111101 .

If you had a conditional that was only valid under these conditions, you could do something like this:

if(state[0] && state[1] && state[2] && state[3] && state[4] 
&& state[5] && !state[6] && state[7]){
  // something something

Because these states have little meaning by themselves, one potential refactoring would be to move these conditions into a function:

if(stateIsOk()){
  // something something
...

stateIsOk = function(state){
  return state[0] && state[1] && state[2] && state[3] && state[4] &&
    state[5] && !state[6] && state[7]
}

But if you stored your state in a bit field, you could do this instead:

if(state===0b11111101){
  // something something

// or you can give this state a more specific name

if(stateIsOk()){
  // something something
...

stateIsOk = function(state){
  return state===0b11111101;
}

This has more potential for performance optimization than refactoring, because bit-wise arithmetic is super fast, but it’s a little tricky to work with in many applications. If you’re doing something that is graphically intensive and/or needs to be fast (like a game), keep this array-like representation in mind.

Extracting this function is nice because we can easily describe (via the function name) what 0b11111101 actually means. Speaking of extracting functions, we’re about to do a whole bunch of that in the next section.

Testing What We Have

For our changes so far, we could limp along without needing to pull in a testing framework, instead manually testing with console.log . Everyone has a different tolerance for how big and complex a project should be before tooling up certain aspects, including testing. For some, visually inspecting the correct output might have been enough of a hassle to motivate testing early on. Others might have felt a lack of confidence due to not testing low-level functions from the very start.

On the other hand, there is a case for sticking with high-level tests (even manual ones like ours) until your code begins to take a bit more shape. Many tests that cover low-level refactorings may provide extra work without extra confidence.

For instance, if you know that you have dead code, do you want to test it before you delete it? If you have a function that you know you want to rename, do you really want to test it beforehand?

Four More Testing Philosophies

The combination of unit and high-level testing in JavaScript (including testing private functions when you feel like, and using TDD when it works well for you and your team) is fairly mainstream, although this book emphasizes characterization tests because they are terribly underrated.

It is a good approach to be comfortable with, and tends to mesh well with most teams. However, there are a few other testing philosophies that are worth considering:

Unit tests are a waste of time (only high-level tests/metrics matter)

I’ve never heard this from a competent engineer who is currently working on coding tasks, rather than as a manager or consultant focused more on high-level goals.

TATFT (Test All The [Redacted] Time)

In this approach, you test it all. You test your dependencies. You test your tests. You test everything . I’ve never personally seen people adapt this in practice, but I’ve definitely seen it inspire people to write more tests.

If it compiles (or type checks ), it works

For languages that care about type safety (like Haskell or the compiles-to-JS variant, PureScript), many errors simply won’t happen, because the errors will come up at compile time. However, even in the case of type-safe, idempotent, pure functions, logic errors are still possible, so using a functional language doesn’t actually let you off the hook for testing.

UUM (Uses Until Modification)

This is a nuanced view on testing that suggests the degree to which you test code should be proportional to how much it will be used before it is modified. If it’s in your editor, actively being worked on, then it will be used zero times before it’s modified, so no test is necessary. If it’s headed out into the world where millions of people will use it (whether it’s a developer library or something facing the general public), then it should have more tests. The original post is only a few bullet points long, and worth a look.

In this chapter, our changes are much more aggressive. In order to approach those changes with confidence, we’re going to need more tests. Before we make any more changes, we’re going to test what we have now.

In case it isn’t obvious what we want to test, the premise is that we want to convert our manual workflow into an automated one. That means that anything that we’ve been looking to for output should be inside of a test.

Code wanting to be better

If you look at code in a certain way, you can see how it wants to be better. Long files want to be shorter. Comments explaining a few lines of code want to be functions, named with the comment, that wrap up those few lines. As it applies to us right now, these logging statements want to be functions.

Our Setup Test

Before we start testing the actual behavior of our code, it’s useful to have a test to just ensure that everything is working properly. 

Add this to the bottom of your file:

var wish = require('wish');
describe('the file', function() {
  it('works', function(){
    wish(true);
  });
});

Note that you may also need to run these commands from the command line:

npm install -g mocha
npm install wish

Now if you run mocha nb.js you should see a passing test as well as our logging information.

Don’t forget about the watcher

Don’t forget about using mocha -w nb.js to run the watcher in a terminal window to update the results when you make changes.

Characterization Tests for classify

Instead of using console.log at the end of functions, we can actually return something from them that we can test. Add this inside the describe block (the classify line is the same as before):

it('classifies', function(){
  classify(['f#m7', 'a', 'dadd9', 'dmaj7', 'bm', 'bm7', 'd', 'f#m']);
});

Next, at the very end of the classify function, have it return in addition to logging:

function classify(chords){
...
  });
  console.log(classified);
  return classified;  // this line is new
};

Back to the test: we know that, since we’re lacking coverage, we want to write a characterization test. Let’s use the characterization mode of wish by supplying a second parameter of true , and let the test output tell us what the output is.

Make the "classifies" test look like this:

it('classifies', function(){
  var classified = classify(['f#m7', 'a', 'dadd9', 
                             'dmaj7', 'bm', 'bm7', 'd', 'f#m']);
  wish(classified.get('easy'), true);
  wish(classified.get('medium'), true);
  wish(classified.get('hard'), true);
});

After running mocha , this leads to:

WishCharacterization: classified.get('easy') 
  evaluated to 1.3433333333333333

And then we can just put that value into our test:

// replace this
wish(classified.get('easy'), true);

// with this
wish(classified.get('easy') === 1.3433333333333333);

Run mocha again and we get:

WishCharacterization: classified.get('medium') 
  evaluated to 1.5060259259259259

Perfect. Again, we replace the , true with the output value:

wish(classified.get('medium') === 1.5060259259259259);

Save and run mocha . Once again, we get a characterization error:

WishCharacterization: classified.get('hard')
  evaluated to 1.6884223991769547

Now we have the information we need for the full test block:

it('classifies', function(){
  var classified = classify(['f#m7', 'a', 'dadd9', 
                             'dmaj7', 'bm', 'bm7', 'd', 'f#m']);
  wish(classified.get('easy') === 1.3433333333333333);
  wish(classified.get('medium') === 1.5060259259259259);
  wish(classified.get('hard') === 1.6884223991769547);
});

Following that same process again, we can write a similar test for the other song we are classifying:

it('classifies again', function(){
  var classified = classify(['d', 'g', 'e', 'dm']);
  wish(classified.get('easy') === 2.023094827160494);
  wish(classified.get('medium') === 1.855758613168724);
  wish(classified.get('hard') === 1.855758613168724);
});

Now we can remove three things:

  • Our logging statement ( console.log(classified); ) from the classify function
  • The calls to classify that are outside of the tests
  • The "works" test that we added to make sure our setup was okay

You might be wondering why we didn’t just copy the values from the console.log statement and put them in the test. The reason is so we could have a test failure first. If we don’t see a failure, we can’t be totally certain that the specific action we took is actually what made the test pass. “Things seem to be functioning correctly” is not as confident of a statement as “I changed the test expectation to match the result of the failing characterization test, and that turned the test from red to green.” That might seem subtle, but small steps are easier to undo.

Testing the welcomeMessage

Now let’s add a new test for the welcome message (inside of the describe block). This time, instead of leaving our  logging statement in place, we’ll move it into a test:

// delete this line from the file (near the top)
console.log(`Welcome to ${fileName()}!`);

// add this test inside of the describe block
it('sets welcome message', function(){
  console.log(`Welcome to ${fileName()}!`);
});

Right now, this passes, as there is no assertion made. But we still see the output from the logging statement, so we know the code still works. Let’s add the assertion now:

it('sets welcome message', function(){
  console.log(`Welcome to ${fileName()}!`);
  wish(welcomeMessage() === 'Welcome to nb.js!') // this line is new
});

Note that we’re intending to add a function here. This is not a characterization test. This is a unit test for a function that hasn’t been written yet.

We get an error:

ReferenceError: welcomeMessage is not defined

Great. Let’s define that function at the top of the file:

function welcomeMessage(){
  return `Welcome to ${fileName()}!`;
};

The test now passes. This means we no longer need to rely on the welcome message logging statement anywhere, including in our test, so we can just have the following:

it('sets welcome message', function(){
  wish(welcomeMessage() === 'Welcome to nb.js!')
});

Testing for labelProbabilities

Here, we’ll take the same approach of moving the logging statement into a test, and then making it into a proper assertion. To start, delete this line from the classify function:

console.log(labelProbabilities);

And add this code inside of the describe block:

it('label probabilities', function(){
  console.log(labelProbabilities);
});

We can change that to a characterization test like this:

it('label probabilities', function(){ 
  wish(labelProbabilities, true);
});

When we run the test, our output tells us what we need to do next:

WishCharacterization: labelProbabilities
evaluated to [["easy",0.3333333333333333],
              ["medium",0.3333333333333333],
              ["hard",0.3333333333333333]]

Since we know that we’re dealing with labelProbabilities as a set, we can test individual components like this:

it('label probabilities', function(){
  wish(labelProbabilities.get('easy') === 0.3333333333333333);
  wish(labelProbabilities.get('medium') === 0.3333333333333333);
  wish(labelProbabilities.get('hard') === 0.3333333333333333);
});

Now that we have high-level tests in place, we can refactor aggressively and with confidence. Also, we’re completely free from console.log statements.

Extracting Functions

Here we go! This section is about what, as we said in the last chapter, is likely the most useful and underutilized refactoring technique: extracting functions.

Getting Away from Procedural Code

If we look through the code at this point, we might notice that we have data (songs and labels) mixed in with our functions. Overall, our program looks like it has these steps:

  1. Set up data (songs and labels).
  2. Set up objects, sets, and maps.
  3. Train our classifier on the set of songs.
  4. Set counts and probabilities.
  5. Classify with new songs (handled by the tests).

Right now, the first four steps are still spelled out awkwardly in a procedural and unstructured way.

We want to get away from running the file , and start to think about executing functions . That means that anything not inside of a function or the testing code is a problem .

The following functions are always run together:

setLabelProbabilities();
setChordCountsInLabels();
setProbabilityOfChordsInLabels();

That means we can wrap them in another function and run that immediately, like this:

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  setChordCountsInLabels();
  setProbabilityOfChordsInLabels();
};
setLabelsAndProbabilities();

Note that we could also run this as an anonymous IIFE (immediately invoked function expression; see “Function Calls and Function Literals” ), like this:

(function(){
  setLabelProbabilities();
  setChordCountsInLabels();
  setProbabilityOfChordsInLabels();
})();

But in doing that we lose some control. If we ever decided to call this more than once, we’d have to name it or find a way to run the code containing it each time.

For now, it doesn’t actually matter when this function is called, as long as it is called just once: after the classifier is trained, but before we run classify .

Let’s add a trainAll function and call setLabelsAndProbabilities at the end of it. We won’t call it anywhere else. Also, let’s add a call to trainAll right after its declaration:

function trainAll(){
  train(imagine, easy);
  train(somewhereOverTheRainbow, easy);
  train(tooManyCooks, easy);
  train(iWillFollowYouIntoTheDark, medium);
  train(babyOneMoreTime, medium);
  train(creep, medium);
  train(paperBag, hard);
  train(toxic, hard);
  train(bulletproof, hard);
  setLabelsAndProbabilities();
};

trainAll();

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  setChordCountsInLabels();
  setProbabilityOfChordsInLabels();
};

We want trainAll to be part of our public interface (a function that we run, rather than part of a file that we run) just like any other statement, so we should move it to be called right inside of the describe block of our tests:

describe('the file', function() {
  trainAll();

Next, we can extract a function for setting our songs and (for now) call it right away:

function setSongs(){
  imagine = ['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'];
  somewhereOverTheRainbow = ['c', 'em', 'f', 'g', 'am'];
  tooManyCooks = ['c', 'g', 'f'];
  iWillFollowYouIntoTheDark = ['f', 'dm', 'bb', 'c', 'a', 'bbm'];
  babyOneMoreTime = ['cm', 'g', 'bb', 'eb', 'fm', 'ab'];
  creep = ['g', 'gsus4', 'b', 'bsus4', 'c', 'cmsus4', 'cm6'];
  paperBag = ['bm7', 'e', 'c', 'g',
              'b7', 'f', 'em', 'a',
              'cmaj7', 'em7', 'a7', 'f7',
              'b'];
  toxic = ['cm', 'eb', 'g', 'cdim', 'eb7', 'd7', 'db7', 'ab',
           'gmaj7', 'g7'];
  bulletproof = ['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'];
};
setSongs();

We know that we want this to happen once before training, so we can move our setSongs function call (the last line of the previous snippet) to be inside trainAll :

function trainAll(){
  setSongs();
...

As always, after each of these changes, you should be noting the passing test suite and committing the results.

We want to do the same with the setup of difficulty variables and our containers (array, sets, and maps) that we use throughout the program, but if we take the same approach of extracting a function, our test suite will give an error. Try this:

function setDifficulties(){
  var easy = 'easy';
  var medium = 'medium';
  var hard = 'hard';
};
setDifficulties();

If we do this, our variables are stuck inside that function’s scope, and no longer readable by other functions.  Later, we’ll be addressing how to tighten up the scopes for these variables, but for now, we can take the easy way out and leave these as global variables by omitting the var keyword:

function setDifficulties(){
  easy = 'easy';
  medium = 'medium';
  hard = 'hard';
};
setDifficulties();

And we can do the same for our other global variables (move them into a function, remove the scoping declaration, and call the function):

function setup(){
  songs = [];
  allChords = new Set();
  labelCounts = new Map();
  labelProbabilities = new Map();
  chordCountsInLabels = new Map();
  probabilityOfChordsInLabels = new Map();
};
setup();

Next, we can move the function calls into our trainAll function:

function trainAll(){
  setDifficulties();
  setup();
  setSongs();
...

Make sure to remove those three calls ( setDifficulties , setup , and setSongs ) from other places in the program. Assuming you’ve done that, now everything is either inside of a function or the test code.

Oh No! var Was Deleted! Everything Is Worse Now!

And we didn’t even have var declarations for our songs to begin with! Bad code!

Right?

We’ll talk about var and other scoping declarations later. For now, recognize that our program relied on these as global variables before. We’re just no longer using the var keyword to pretend they’re not global.

One way to fix this is by specifically scoping and passing them into each function that requires them. Done naively, this path would require a lot of changes, including more complex method signatures (more parameters) and more return values.

At some point, we’ll want to attach these variables to some object other than the global one, but for now, it’s a win to have the interface well defined by the tests: they just run trainAll and classify , which means we’re more concerned with the contents of the file as opposed to the order .

Great. So now everything is inside of a function and our interface for the tests is well defined. We could extract more functions if we wanted to get more specific in places. For instance, we could change our setup function to do something like this instead (but don’t do this):

function setSongsVariable(){
  songs = [];
};
function setup(){
  setSongsVariable();
  allChords = new Set();
  labelCounts = new Map();
  labelProbabilities = new Map();
  chordCountsInLabels = new Map();
  probabilityOfChordsInLabels = new Map();
};

And we could do that with the rest of the lines in setup as well. Or we could use it to arbitrarily group some lines inside (don’t do this either):

function setSome(){
  songs = [];
  allChords = new Set();
  labelCounts = new Map();
};
function setOthers(){
  labelProbabilities = new Map();
  chordCountsInLabels = new Map();
  probabilityOfChordsInLabels = new Map();
};
function setup(){
  setSome();
  setOthers();
};

We can add as much indirection as we’d like by extracting functions, and use this technique to group things where it makes sense. But these changes don’t actually help our code be more clear. We’re just grouping arbitrary lines at this point.

The opposite of extracting functions is inlining them. When an extracted function  doesn’t really do anything, it’s sensible to inline it. If you did extract those functions, inline them now and restore the setup function to how it was:

function setup(){
  songs = [];
  allChords = new Set();
  labelCounts = new Map();
  labelProbabilities = new Map();
  chordCountsInLabels = new Map();
  probabilityOfChordsInLabels = new Map();
};

If you’re wondering what the point of that was, it’s that extracting and inlining functions should come as naturally to you as introducing and inlining variables.

Extracting and Naming Anonymous Functions

In addition to extracting functions helping to group behavior, it is also useful for naming anonymous functions.  We have some anonymous functions in our program. For examples, look at any code that follows a forEach , or the second parameter to the describe and it function calls in the test.

We could extract some of these functions, but to demonstrate the benefits a bit more simply, let’s take a look at some pedestrian jQuery code that visits a URL when a button is clicked:

$('.my-button').on('click', function(){
  window.location = "http://refactoringjs.com";
});
$('.other-button').on('click', function(){
  window.location = "http://refactoringjs.com";
});

Some people would correctly identify that duplication as a maintenance problem deserving of some kind of fix. Unfortunately, many of them would jump to this solution, simply extracting a variable, and stop there:

var siteUrl = "http://refactoringjs.com";
$('.my-button').on('click', function(){
  window.location = siteUrl;
});
$('.other-button').on('click', function(){
  window.location = siteUrl;
});

This does make it easier to change siteUrl in the future (assuming it is used in other places), but we can reduce duplication further by extracting a function:

var siteUrl = "http://refactoringjs.com";
function visitSite(){
  window.location = siteUrl;
} 
$('.my-button').on('click', function(){
  visitSite();
});
$('.other-button').on('click', function(){
  visitSite();
});

Now our implementation will be easier to change in the future, but what good does wrapping our function call in a function accomplish? Nothing! Try this instead:

var siteUrl = "http://refactoringjs.com";
function visitSite(){
  window.location = siteUrl;
}
$('.my-button').on('click', visitSite);
$('.other-button').on('click', visitSite);

Now we can keep our click handlers together. This organization is much better.

Function Calls and Function Literals

For programmers who are new to JavaScript or those who mostly work in some other language on the backend, there is often some confusion over function syntax that makes this type of refactoring difficult for them.

This is an anonymous function literal:

function(){};

This is a named function literal:

function visitSite(){};

This is an anonymous function literal assigned to a variable:

var visitSite = function(){};

This is a function call:

visitSite();

The only way to call an anonymous function (the first one, when it is not assigned to a variable as in the third snippet) is by running the containing code:

(function(){})();
// or
(function(){}());

This is called an IIFE (“iffy”), or immediately invoked function expression . And it is a function call (i.e., invocation ).

The confusion arises when people don’t realize that an anonymous function declaration, when replaced with a named function for reuse, can be used in the same way as a function reference :

$('.my-button').on('click', visitSite);

and not with a function call like this:

$('.my-button').on('click', visitSite());

You should be passing a reference to the visitSite function into the on function, not a function call.

Additional confusion arises when a parameter is used by the function being referenced. If our function looked like this:

function visitSite(siteUrl){
  window.location = siteUrl;
};

some people would be tempted to write the click handler like this:

$('.my-button').on('click', visitSite("http://refactoringjs.com"));

But that won’t work. In this case, the most obvious solution would be using an anonymous function to wrap the call like before:

$('.my-button').on('click', function(){
  visitSite("http://refactoringjs.com");
});

Another solution, which applies not only to the on function of jQuery but to native JavaScript functions like forEach and map as well, is to pass another argument along with the others. In many cases, what you pass will end up being the “implicit” parameter (the this ) of the function that you are calling, but if you are defining a function taking a function as an argument, you could also design the function signature to take arguments that will become explicit arguments to the function passed.

In any case, when you are passing functions inside of functions, you should keep two things in mind. First, consult the API of the function that takes a function as an argument for any optional arguments that can be passed in, and know what happens when they are not. Second, recognize that JavaScript function calls will work fine with too many or too few arguments. You will get an error inside of the function if you try to call it and make use of a parameter that was not defined by the signature. Also, any parameters that are unfulfilled by the function call will be set as undefined . 

Streamlining the API with One Global Object

At this point, we have everything wrapped up into functions, but we still have many global variables floating around (this includes our functions as well as variables set without var ). In this section, we have two goals. The first is to reduce the scope of all of the global variables we have. The second is to design our API—in other words, make decisions about how our code will be used.

For the style of code we’re exploring here, we want one main object, which we will call classifier , and it will hold all of the functions and incidental variables created along the way. We’ll explore its creation through multiple mechanisms (factory function, constructor function, and class), and in all cases, we’ll be working with it in an OOP fashion. That means we’ll be using language constructs like this and allowing our classifier object to mutate throughout the execution of our program.

If you’d prefer to work toward a functional approach, rather than an OOP one, some of what follows will not follow the path you want to go. For that path, I would recommend still reading through the rest of this chapter and then looking into Chapter 11 . But the time we spend “ this -ifying” for the OOP style here will need extra work to convert to FP style. The reason is that OOP will lead us to having a main mutable object (although it could reasonably break down into smaller objects), whereas in FP, we want to treat our bounding object ( classifier ) as more of a dumb namespace for functions.

A functional version of our NBC is provided in Chapter 11 . If you’re interested in getting to that point, try starting from the code we have here as well as the code you have at the end of this chapter. I suspect you’ll find code that is split into functions (but not as heavily invested in OOP as the code at the end of this chapter), like we have at this point, easier to work with. By all means, try both approaches if that interests you.

For the rest of the chapter, we’ll be ignoring the welcomeMessage and fileName functions, as well as the accompanying test. In case you’re lost at this point, or want to build an FP version starting from what we have now, here is the code:

function setDifficulties(){
  easy = 'easy';
  medium = 'medium';
  hard = 'hard';
};

function setSongs(){
  imagine = ['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'];
  somewhereOverTheRainbow = ['c', 'em', 'f', 'g', 'am'];
  tooManyCooks = ['c', 'g', 'f'];
  iWillFollowYouIntoTheDark = ['f', 'dm', 'bb', 'c', 'a', 'bbm'];
  babyOneMoreTime = ['cm', 'g', 'bb', 'eb', 'fm', 'ab'];
  creep = ['g', 'gsus4', 'b', 'bsus4', 'c', 'cmsus4', 'cm6'];
  paperBag = ['bm7', 'e', 'c', 'g',
              'b7', 'f', 'em', 'a',
              'cmaj7', 'em7', 'a7', 'f7',
              'b'];
  toxic = ['cm', 'eb', 'g', 'cdim', 'eb7', 'd7', 'db7', 'ab',
           'gmaj7', 'g7'];
  bulletproof = ['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'];
};

function setup(){
  songs = [];
  allChords = new Set();
  labelCounts = new Map();
  labelProbabilities = new Map();
  chordCountsInLabels = new Map();
  probabilityOfChordsInLabels = new Map();
};

function train(chords, label){
  songs.push({label, chords});
  chords.forEach(chord => allChords.add(chord));
  if(Array.from(labelCounts.keys()).includes(label)){
    labelCounts.set(label, labelCounts.get(label) + 1);
  } else {
    labelCounts.set(label, 1);
  }
};

function setLabelProbabilities(){
  labelCounts.forEach(function(_count, label){
    labelProbabilities.set(label,
                           labelCounts.get(label) / songs.length);
  });
};

function setChordCountsInLabels(){
  songs.forEach(function(song){
    if(chordCountsInLabels.get(song.label) === undefined){
      chordCountsInLabels.set(song.label, {});
    }
    song.chords.forEach(function(chord){
      if(chordCountsInLabels.get(song.label)[chord] > 0){
        chordCountsInLabels.get(song.label)[chord] += 1;
      } else {
        chordCountsInLabels.get(song.label)[chord] = 1;
      }
    });
  });
}

function setProbabilityOfChordsInLabels(){
  probabilityOfChordsInLabels = chordCountsInLabels;
  probabilityOfChordsInLabels.forEach(function(_chords, difficulty){
    Object.keys(probabilityOfChordsInLabels.get(difficulty)).forEach(
function(chord){
      probabilityOfChordsInLabels.get(difficulty)[chord]
/= songs.length;
    });
  });
}

function trainAll(){
  setDifficulties();
  setup();
  setSongs();
  train(imagine, easy);
  train(somewhereOverTheRainbow, easy);
  train(tooManyCooks, easy);
  train(iWillFollowYouIntoTheDark, medium);
  train(babyOneMoreTime, medium);
  train(creep, medium);
  train(paperBag, hard);
  train(toxic, hard);
  train(bulletproof, hard);
  setLabelsAndProbabilities();
};

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  setChordCountsInLabels();
  setProbabilityOfChordsInLabels();
};

function classify(chords){
  var smoothing = 1.01;
  var classified = new Map();
  labelProbabilities.forEach(function(_probabilities, difficulty){
    var first = labelProbabilities.get(difficulty) + smoothing;
    chords.forEach(function(chord){
      var probabilityOfChordInLabel =
probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        first = first * (probabilityOfChordInLabel + smoothing);
      }
    });
    classified.set(difficulty, first);
  });
  return classified;
};

var wish = require('wish');
describe('the file', function() {
  trainAll();
  it('classifies', function(){
    var classified = classify(['f#m7', 'a', 'dadd9',
                               'dmaj7', 'bm', 'bm7', 'd', 'f#m']);
    wish(classified.get('easy') === 1.3433333333333333);
    wish(classified.get('medium') === 1.5060259259259259);
    wish(classified.get('hard') === 1.6884223991769547);
  });
  it('classifies again', function(){
    var classified = classify(['d', 'g', 'e', 'dm']);
    wish(classified.get('easy') === 2.023094827160494);
    wish(classified.get('medium') === 1.855758613168724);
    wish(classified.get('hard') === 1.855758613168724);
  });
  it('label probabilities', function(){
    wish(labelProbabilities.get('easy') === 0.3333333333333333);
    wish(labelProbabilities.get('medium') === 0.3333333333333333);
    wish(labelProbabilities.get('hard') === 0.3333333333333333);
  });
});

Extracting the classifier Object

To our global variables (and functions) we’ll create an object called classifier to store them, so that they’re not attached directly to the global object. Put this the top of your file:

var classifier = {};

Then, inside of trainAll , instead of setup being run as a function of the global object, call it as part of this classifier :

function trainAll(){
  classifier.setup(); // this line is new
  setDifficulties();
  setup(); // get rid of this one
...

Now we need to move our setup function into our classifier object, at the top of the file. You can also delete the old setup function:

var classifier = {
  setup: function(){
    this.songs = [];
    this.allChords = new Set();
    this.labelCounts = new Map();
    this.labelProbabilities = new Map();
    this.chordCountsInLabels = new Map();
    this.probabilityOfChordsInLabels = new Map();
  };
};

We want these variables to be part of classifier , so we need to add a this. in front of each of them. Notice that setup is a property with the label ( setup ) followed by a function literal that contains the body of the function.

It would be great if the tests passed at this point, but they don’t. Fortunately, running the tests will report a useful error:

ReferenceError: songs is not defined

And here we have some very boring and repetitive, but relatively easy, changes to make. We need to add a classifier. in front of every reference to the following variables (that don’t start with this. ): songs , allChords , labelCounts , labelProbabilities , chordCountsInLabels , and probabilityOfChordsInLabels . Make those changes now.

The tests should pass again. Save and commit those changes.

Inlining the setup Function

Now that we look at our setup function attached to classifier , however, we might notice that it’s not doing much work. We can assign those variables directly to the object without using a wrapping function at all:

var classifier = {
  songs: [],
  allChords: new Set(),
  labelCounts: new Map(),
  labelProbabilities: new Map(),
  chordCountsInLabels: new Map(),
  probabilityOfChordsInLabels: new Map()
};

Notice that the function wrapping is gone, but the syntax inside has also been tweaked. For example, instead of this:

this.songs = [];

we now have this:

songs: [],

The comma versus semicolon is easy to miss. And we can also delete the call to setup in trainAll :

function trainAll(){
  classifier.setup(); // delete this line
...

That’s great, not only because we have one less line, but also because our training code really doesn’t have anything to do with the general setup of our classifier .

Save/test/commit to make sure everything still looks good.

Extracting the songList Object

Next let’s consider how we’re adding songs to be trained. setSongs defines global variables for each song name, and then each of those is referenced in the trainAll function.  This coupling is error prone and not really scalable. Clearly, if we alter our list of songs, we have to do it in two places. But worse than that, we are not prepared for a likely case where we would have a database of songs to train, rather than a handful that we hardcode into a file .

Let’s make a songList object that contains the songs in an array and has a function to add songs to it. This can go at the top of your file:

var songList = {
  songs: [],
  addSong: function(name, chords, difficulty){
    this.songs.push({name: name,
                    chords: chords,
                    difficulty: difficulty});
  }
};

Now let’s change our setSongs function to make use of this songList object:

function setSongs(){
  songList.addSong('imagine',
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], easy)
  songList.addSong('somewhereOverTheRainbow',
['c', 'em', 'f', 'g', 'am'], easy)
  songList.addSong('tooManyCooks', ['c', 'g', 'f'], easy)
  songList.addSong('iWillFollowYouIntoTheDark',
['f', 'dm', 'bb', 'c', 'a', 'bbm'], medium);
  songList.addSong('babyOneMoreTime',
['cm', 'g', 'bb', 'eb', 'fm', 'ab'], medium);
  songList.addSong('creep',
['g', 'gsus4', 'b', 'bsus4', 'c', 'cmsus4', 'cm6'], medium);
  songList.addSong('paperBag',
['bm7', 'e', 'c', 'g', 'b7', 'f', 'em',
'a', 'cmaj7', 'em7', 'a7', 'f7',
'b'], hard);
  songList.addSong('toxic',
['cm', 'eb', 'g', 'cdim', 'eb7', 
'd7', 'db7', 'ab', 'gmaj7', 'g7'], hard);
  songList.addSong('bulletproof',
['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'], hard);
};

If we run the tests now, we get errors because our variables named by the song names are no longer available. We need to change our trainAll function to add the songs from the songList :

function trainAll(){
  setDifficulties();
  setSongs();
  songList.songs.forEach(function(song){
    train(song.chords, song.difficulty);
  });
  setLabelsAndProbabilities();
};

And now our tests are back in working order.

Handling the Remaining Global Variables

We’re still left with those three nagging global variables to represent difficulty.

As a first effort, since they are only referenced inside of setSongs , we can simply inline the variables there:

function setSongs(){
  var easy = 'easy';
  var medium = 'medium';
  var hard = 'hard';
...

And now we can delete the function setDifficulties and our call to it inside of trainAll . Tests should be passing at this point.

Following that, it might seem a waste to complicate our setSongs function with these variables. What if we just used an array for difficulties , and let the songList handle the strings?

var songList = {
  difficulties: ['easy', 'medium', 'hard'],
  songs: [],
  addSong: function(name, chords, difficulty){
    this.songs.push({name: name,
                    chords: chords,
                    difficulty: this.difficulties[difficulty]})
  }
};

Here, we’ve created a difficulties attribute in songList as an array with the desired labels. Then, when we add a song, we’re expecting the array index to come through and assigning as needed with this.difficulties[difficulty] .

This means we can get rid of the label description noise in setSongs and use numbers instead of the variables we were using before. Notice the numbers as the third parameter of the addSong function calls:

function setSongs(){
  songList.addSong('imagine',
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], 0);
  songList.addSong('somewhereOverTheRainbow',
['c', 'em', 'f', 'g', 'am'], 0);
  songList.addSong('tooManyCooks', ['c', 'g', 'f'], 0);
  songList.addSong('iWillFollowYouIntoTheDark',
['f', 'dm', 'bb', 'c', 'a', 'bbm'], 1);
  songList.addSong('babyOneMoreTime',
['cm', 'g', 'bb', 'eb', 'fm', 'ab'], 1);
  songList.addSong('creep',
['g', 'gsus4', 'b', 'bsus4', 'c', 'cmsus4', 'cm6'], 1);
  songList.addSong('paperBag',
['bm7', 'e', 'c', 'g', 'b7', 'f', 'em',
 'a', 'cmaj7', 'em7', 'a7', 'f7',
 'b'], 2);
  songList.addSong('toxic',
['cm', 'eb', 'g', 'cdim', 'eb7', 'd7', 'db7', 'ab', 'gmaj7', 'g7'], 2);
  songList.addSong('bulletproof',
['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'], 2);
};

Save/test/commit.

Making Data Independent from the Program

Let’s think about that trainAll function for a minute. What does setting songs have to do with training our classifier? Nothing at all, really. What if we move the call to setSongs into our test?

describe('the file', function() {
  setSongs(); // moved and deleted from inside of trainAll
  trainAll();

And while we’re at it, does setting the songs have anything to do with the structure of our program at all? No. It’s only data that we are setting and using. That means it is part of the execution of one possibility of our program, not the program itself. That implies that the function of setSongs itself belongs in the tests. Let’s inline the function body into the tests and remove the function from the program completely:

describe('the file', function() {
  songList.addSong('imagine',
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], 0);
  songList.addSong('somewhereOverTheRainbow',
['c', 'em', 'f', 'g', 'am'], 0)
  songList.addSong('tooManyCooks', ['c', 'g', 'f'], 0);
...
  songList.addSong('bulletproof',
['d#m', 'g#', 'b', 'f#', 'g#m', 'c#'], 2);
  trainAll();
...

Now we’re free to execute the program independently of the data provided. This is a huge step, and opens our program up to further testing and putting it into production as a module.

Scoping Declarations: var, let, and const

Moving on to other scoping concerns, let’s talk about scoping declarations: var , let , and const . var has been around for the longest, so you’re most likely to find it in older codebases or code written by people who are stuck in an older mindset. Although var is better than nothing (a variable declaration, and necessarily an assignment, without any scoping declaration will create a global variable), let and const create tighter scopes (block scope rather than just functional scope). The difference between let and const is that const will not allow a variable to be reassigned.

We have nine instances of var in our program right now. Should we change any of them? If so, should they change to let or const ?

const does not mean immutability!

If you are thinking that const provides an easy path to immutability, I’m sorry to report some sad news. It does prevent a variable from being reassigned (i.e., through the = operator), but the contents of the variable can still change. Array indexes can be updated. The same goes for object attributes and members of sets and maps.

Object.freeze to the rescue!? Almost. If you freeze an object that is more than one level deep, you can still update those inner properties. Also, even if you freeze an object, if it was declared with var or let , you can still reassign it.

To ensure immutability, you’ll need to go further, and might find it easier to use a packaged solution like Immutable.js or mori, which provide immutable versions of arrays, maps, sets, and so on. Even if you’re not using anything that enforces it, it’s best to try to create new variables rather than repurposing them.

In general, it’s preferable to use const . The less that your variables are reassigned, the better.

Since we have tests in place, we can make the bold assumption that all of our var declarations should be const instead. Search and replace those, and then run the tests. You’ll get an error:

TypeError: Assignment to constant variable.

The error description “constant variable” is worth noting as an odd oxymoron, but let’s move on. Unsurprisingly, our bold assumption is wrong, but only in one case. Our first variable inside of the classify function requires reassignment for now, so the following line should be modified to use let :

const first = classifier.labelProbabilities.get(difficulty) +
smoothing;

It should be:

let first = classifier.labelProbabilities.get(difficulty) +
smoothing;

All the rest of the const declarations are fine, and we’re free to move on.

Bringing classify into the classifier

With a few changes, the variable first doesn’t have to be reassigned, though. Initially, it is meant to reflect the likelihood of a difficulty appearing relative to other difficulties. Later, it is multiplied by the likelihood of a chord existing in a song of a given difficulty.

What if instead of reassigning that variable, we introduced a likelihoods array that would capture all of the values we need to multiply together, and then multiplied them?

function classify(chords){
  const smoothing = 1.01;
  const classified = new Map();
  classifier.labelProbabilities.forEach(
function(_probabilities, difficulty){
    const likelihoods = [classifier.labelProbabilities.get(difficulty)
+ smoothing];
    chords.forEach(function(chord){
      const probabilityOfChordInLabel =
classifier.probabilityOfChordsInLabels.get(difficulty)[chord]
      if(probabilityOfChordInLabel){
        likelihoods.push(probabilityOfChordInLabel + smoothing)
      }
    })
    const totalLikelihood = likelihoods.reduce(function(total, index) {
      return total * index;
    });
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
};

We’ve mentioned, but haven’t gone into depth on, the reduce function . It allows us to step through an array and apply some function to it, while working with a returned value, along with each element.

But wait! We already have an array that we’re looping through ( chords ). Why would we create a new one to step through? Do we really need to loop twice (once to accumulate and once to multiply)? Let’s try using reduce on that forEach instead:

function classify(chords){
  const smoothing = 1.01;
  const classified = new Map();
  classifier.labelProbabilities.forEach(
function(_probabilities, difficulty){

// reduce starts
    const totalLikelihood = chords.reduce(function(total, chord){
      const probabilityOfChordInLabel =
classifier.probabilityOfChordsInLabels.get(difficulty)[chord]
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing)
      }else{
        return total;
      }
    }, classifier.labelProbabilities.get(difficulty) + smoothing)
// reduce ends

    classified.set(difficulty, totalLikelihood);
  });
  return classified;
};

This is a bit more complex, for two reasons. First, our initial likelihood is now at the end, just above this line: //reduce ends . This supplies the “initial value” to the reduce total. Second, the else branch of our if statement is back.  The reason is that on every step through the reduce function, if nothing is returned (which would be the case if the if condition was false and we had no else branch), then undefined would be returned. Returning the total has the same effect as just moving on to the next element.

If that’s confusing, think of it this way. Say you had a reduce function like this:

[2, 3, 4].reduce(function(result, element){ return result }, 10)

This function would simply return 10 . If no value was supplied as the second parameter (if the , 10 was not there), it would return the first element: 2 . This is because result is fed back into the function for each element. Contrast this with another simple use of reduce , which sums the values of an array:

[2, 3, 4].reduce(function(result, element){return result + element })

This will return 9 . If it had an initial element of 10 , it would add that as well, returning 19 .

Back to our example, one pattern that is especially common in JavaScript is to allow unmet conditions to return something outside of an else . For example:

if(probabilityOfChordInLabel){
  return total * (probabilityOfChordInLabel + smoothing);
}
return total;

If the true branch of the if statement isn’t executed, the code will continue beyond it. But personally, I feel this style invites mismatched return types and often visually privileges the less likely possibilities at the top of a function.   Moreover, it less strongly signals two code paths than an explicit if / else , which (if only slightly) disguises the complexity of the code. For someone who is interested in refactoring and thus eliminating complexity, it can mask places that may be good candidates for change.

In any case, you will frequently see this style used for error handling like this:

function callback(error, response){ 
  if(error){
    return new Error(error);
  }
  // do something with the response
}

Now let’s pick on the classify function a bit more. First of all, we should have no issue with tying it more closely to the classifier object. If there’s one obvious thing that a classifier does, it’s classifying.

To that end, let’s move the classify function into the classifier :

const classifier = {
  songs: [],
  allChords: new Set(),
  labelCounts: new Map(),
  labelProbabilities: new Map(),
  chordCountsInLabels: new Map(),
  probabilityOfChordsInLabels: new Map(),
  classify: function(chords){
    const smoothing = 1.01;
    const classified = new Map();
    classifier.labelProbabilities.forEach(
function(_probabilities, difficulty){
      const totalLikelihood = chords.reduce(function(total, chord){
        const probabilityOfChordInLabel =
classifier.probabilityOfChordsInLabels.get(difficulty)[chord]
        if(probabilityOfChordInLabel){
          return total * (probabilityOfChordInLabel + smoothing);
        }else{
          return total;
        }
      }, classifier.labelProbabilities.get(difficulty) + smoothing);
      classified.set(difficulty, totalLikelihood);
    });
    return classified;
  }
};

Our tests will break at this point, because we need to replace instances of classify with classifier.classify in the tests. Change these lines:

const classified = classify(['f#m7', 'a', 'dadd9', 'dmaj7', 
                             'bm', 'bm7', 'd', 'f#m']);
...
const classified = classify(['d', 'g', 'e', 'dm']);

to these:

const classified = classifier.classify(['f#m7', 'a', 'dadd9', 
                                        'dmaj7', 'bm', 'bm7',
                                        'd', 'f#m']);
...
const classified = classifier.classify(['d', 'g', 'e', 'dm']);

Now that our tests are working again (save/test/commit), we still have some work to do with this function. It awkwardly refers to itself in the third person, in a sense. That is, rather than using this , it says its own name: classifier . There are three instances of that. Let’s change those, making the function the following:

classify: function(chords){
  const smoothing = 1.01;
  const classified = new Map();
  this.labelProbabilities.forEach(
function(_probabilities, difficulty){
    const totalLikelihood = chords.reduce(function(total, chord){
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord]
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + smoothing);
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
}

The first instance of this will be fine, but the second and third will cause problems:

  const probabilityOfChordInLabel = 
this.probabilityOfChordsInLabels.get(difficulty)[chord]
// and
}, this.labelProbabilities.get(difficulty) + smoothing)

This is because our this (implicit parameter) is set in the context of the function that contains these statements. The most common and oafish fix is this:

classify: function(chords){
  const smoothing = 1.01;
  const classified = new Map();
  const self = this;
  this.labelProbabilities.forEach(
function(_probabilities, difficulty){
    const totalLikelihood = chords.reduce(function(total, chord){
      const probabilityOfChordInLabel =
self.probabilityOfChordsInLabels.get(difficulty)[chord]
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing);
      }else{
        return total;
      }
    }, self.labelProbabilities.get(difficulty) + smoothing);
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
}

By setting a self variable (in Chapter 5 , we used that instead), you can ensure you have access to the object you want, even within the inner functions. In Chapter 5 , we learned about using call , apply , or bind to accomplish the same thing with a bit more elegance. In this case, since we are not calling these anonymous functions directly, only declaring them to be called by forEach and reduce , we cannot use call or apply to set the implicit argument, this . For this case, we must use bind or find another way.

As for forEach , we can rely on the ability of that function to accept a thisArg as a parameter. This allows us to set what we want this to be in the anonymous function:

this.labelProbabilities.forEach(
  function(_probabilities, difficulty){
    const totalLikelihood = chords.reduce(function(total, chord){
      const probabilityOfChordInLabel =
self.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + smoothing);
    classified.set(difficulty, totalLikelihood);
}, this);

Now that we have added this as a second parameter to forEach (on the last line), we are free to use this rather than self on the third-from-last line. But the remaining call to self cannot yet be changed to this , because its value is wrapped by the anonymous function inside of reduce .

One could reasonably expect that the function signature for reduce ’s callback would also allow a thisArg to be accepted as an optional parameter. Unfortunately, this is not the case, so in this style, the this inside of that function must be set with bind :

  const totalLikelihood = chords.reduce(function(total, chord){
...
  }.bind(this), this.labelProbabilities.get(difficulty) + smoothing);

Now our classify function can be free from the awkward self variable:

classify: function(chords){
  const smoothing = 1.01;
  const classified = new Map();
  this.labelProbabilities.forEach(
function(_probabilities, difficulty){
    const totalLikelihood = chords.reduce(function(total, chord){
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing);
      }else{
        return total;
      }
    }.bind(this), 
    this.labelProbabilities.get(difficulty) + smoothing);
    classified.set(difficulty, totalLikelihood);
  }, this);
  return classified;
}

But before we leave this example, there is another tool we can use to deal with passing our this through: arrow functions. Through them, our function can be simplified like this:

classify: function(chords){
  const smoothing = 1.01;
  const classified = new Map();
  this.labelProbabilities.forEach((_probabilities, difficulty) => {
    const totalLikelihood = chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + smoothing);
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
}

We can now get rid of our this as a second parameter to forEach and our bind(this) in reduce . The arrow functions are in the following lines:

this.labelProbabilities.forEach((_probabilities, difficulty) => {
...
const totalLikelihood = chords.reduce((total, chord) => {

The parts with => are what make them arrow functions. The syntax might seem a little weird (and it has a lot of variation), but what’s great is the this passes through from the outer function.

To simplify this function a bit further, smoothing can be taken out of the function and added as a new attribute of the classifier :

smoothing: 1.01,
classify: function(chords){
  const classified = new Map();
  this.labelProbabilities.forEach((_probabilities, difficulty) => {
    const totalLikelihood = chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + this.smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + this.smoothing);
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
}

On the one hand, this is nice because it gets smoothing out of our function. However, it does increase the scope of where it is available and necessitates adding this. to precede it inside of the function. Extracting this const to an attribute also makes it assignable again. Unfortunately, getting something like a const inside of our classifier object literal takes a bit of work. There is a defineProperty function that we can use to define attributes that are not only not writable, but even immutable by default. We won’t go into depth here, but defineProperty is a good tool to look into if you want a lot of control over how properties are used.

Normally, defineProperty would be called after the object is created, which would add complexity to our execution at some point, and move the attribute’s creation to some other physical place in the file. On the other hand, we could just call this inside of the classify function like this:

classify: function(chords){
  Object.defineProperty(this, 'smoothing', {value: 1.01});

But that puts complexity back into our function, which is what we were trying to avoid by making it an object to begin with. Later, we’ll discuss alternatives to creating objects with object literals, which could give us more control over our properties as the objects are created. But for now, let’s revert this change and allow smoothing to be an attribute as it was.

Another change we can make to the classify function is to inline the classified variable by using the map function instead of forEach . Whenever you find yourself setting up a container (usually an array, but in our case a Map object), using a loop of some kind to change that variable, and then returning the variable, you may be better served by using a map function rather than a loop:

classify: function(chords){
  const classified = new Map();
  Array.from(this.labelProbabilities.entries()).map(
(labelWithProbability) => {
    const totalLikelihood = chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(labelWithProbability[0])[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + this.smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(labelWithProbability[0]) + 
this.smoothing);
    classified.set(labelWithProbability[0], totalLikelihood);
  });
  return classified;
}

Unfortunately, the Map object doesn’t have a map function (yes, it bums me out, too.) So our first step involves pulling an array out of the entries in the Map so that we can use map through it. The second change is that we end up with a slightly less convenient object ( labelWithProbability instead of difficulty ), which requires us to take the first index of [0] . In other words, difficulty is replaced with labelWithProbability[0] . But we can initialize difficulty as a new const :

classify: function(chords){
  const classified = new Map();
  Array.from(this.labelProbabilities.entries()).map(
(labelWithProbability) => {
    const difficulty = labelWithProbability[0];
    const totalLikelihood = chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + this.smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + this.smoothing);
    classified.set(difficulty, totalLikelihood);
  });
  return classified;
}

Now we can almost get rid of our classified variable. Instead of initializing it, updating it in the loop, and returning it after, we can have map return a multidimensional array to set the Map :

classify: function(chords){
  const classified = new Map(Array.from(
    this.labelProbabilities.entries()).map((labelWithProbability) => {
    const difficulty = labelWithProbability[0];
    const totalLikelihood = chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + this.smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + this.smoothing);
    return [difficulty, totalLikelihood];
  }));
  return classified;
}

The second line now includes directly assigning a new Map object to classified . Additionally, our return , four lines from the bottom, now returns an array with difficulty and totalLikelihood . The last (very minor) change to notice is that three lines from the bottom of this sample, we now have an extra closing parenthesis in the line:

})); // just above "return classified;"

And now we’re ready to get rid of the classified variable. Simply delete the line with the last return statement and instead return the result of the call to the new Map constructor :

classify: function(chords){
  return new Map(Array.from(
    this.labelProbabilities.entries()).map((labelWithProbability) => {
...
  }));
}

We now have a similar unnecessary variable in totalLikelihood :

const totalLikelihood = chords.reduce((total, chord) => {
  const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
  if(probabilityOfChordInLabel){
    return total * (probabilityOfChordInLabel + this.smoothing);
  }else{
    return total;
  }
}, this.labelProbabilities.get(difficulty) + this.smoothing);
return [difficulty, totalLikelihood];

Instead of assigning a variable to the result of the reduce call and returning it in the array, we can inline that and return the array directly:

classify: function(chords){
  return new Map(Array.from(
    this.labelProbabilities.entries()).map((labelWithProbability) => {
    const difficulty = labelWithProbability[0];
    return [difficulty, chords.reduce((total, chord) => {
      const probabilityOfChordInLabel =
this.probabilityOfChordsInLabels.get(difficulty)[chord];
      if(probabilityOfChordInLabel){
        return total * (probabilityOfChordInLabel + this.smoothing);
      }else{
        return total;
      }
    }, this.labelProbabilities.get(difficulty) + this.smoothing)];
  }));
}

This might look confusing, but we’re still just returning a two-element array. The first element is difficulty , and the second is the result of the reduce call.

If we want to simplify further, we can extract a function to eliminate our assignment and our conditional inside of this code:

const probabilityOfChordInLabel = 
  this.probabilityOfChordsInLabels.get(difficulty)[chord]
if(probabilityOfChordInLabel){
  return total * (probabilityOfChordInLabel + this.smoothing)
}else{
  return total;
}

We have to delete that assignment, and replace the other two references (one in the conditional’s test and one in the conditional’s if branch) with the righthand side of the assignment. That should leave us with this:

if(this.probabilityOfChordsInLabels.get(difficulty)[chord]){
  return total * 
  (this.probabilityOfChordsInLabels.get(
    difficulty)[chord] + this.smoothing);
}else{
  return total;
}

Next, we extract a function to completely replace those lines with this:

return total * this.valueForChordDifficulty(difficulty, chord);

And we can add a new function above classify :

valueForChordDifficulty(difficulty, chord){
  if(this.probabilityOfChordsInLabels.get(difficulty)[chord]){
    return this.probabilityOfChordsInLabels.get(difficulty)[chord] +
this.smoothing;
  }else{
    return 1;
  }
},

That function will produce a value to multiply by the running total. If we want a slightly denser syntax for that function, we can use the ternary syntax:

valueForChordDifficulty(difficulty, chord){
  const value = 
    this.probabilityOfChordsInLabels.get(difficulty)[chord];
  return value ? value + this.smoothing : 1;
},

Note that this would also work as the first line if you don’t like the function shorthand syntax:

valueForChordDifficulty: function(difficulty, chord){

As opposed to what we have right now, which is:

valueForChordDifficulty(difficulty, chord){
Density and Abstraction

At this point, you might be wondering if this refactoring is really worth it. By inlining variables, we’ve made the code denser. There is also some overhead to using map with a Map object. For some people, inlining variables and using functions like bind is going to make the code harder to read. For others, the arrow syntax, with all of its variation (which we’ll cover later), might be overwhelming. It’s important to be aware of how your style might impact other members of your team.

So did we just make the code worse? Not necessarily. The advantage of inlining variables is twofold. First, less internal state means less to keep track of. Second, inlining variables can make it easier to extract functions, which are more flexible and testable than simple variables.

For both variables and functions, the important part is to be aware of inlining and extracting as choices.

Code has no final, perfect, “refactored” state

One important thing to note about our work on the classify function is that there is no way to tell when you are “done” refactoring. Some refactorings (like inlining and extracting) are inverse processes, so you could end up undoing previous refactoring work with subsequent efforts. You could create an infinite loop of refactoring just due to that fact. Mix in others’ opinions of what “good” code is, and you really can “improve” the code forever. This is part of why it is important to develop your own standards of quality, and to calibrate those with the people you work with.

Untangling Coupled Values

Moving on from our classify function, we have a problem in the code that needs to be addressed. You’ll see something interesting if you add logging statements to the tests (after trainAll(); ) like the following:

console.log(classifier.probabilityOfChordsInLabels);
console.log(classifier.chordCountsInLabels);

They have the same values. Not only that, they actually are referencing the same Set object. 

The reason for this is in the setProbabilityOfChordsInLabels function—specifically, the second line (which spills onto two lines):

function setProbabilityOfChordsInLabels(){
  classifier.probabilityOfChordsInLabels = 
classifier.chordCountsInLabels;
  classifier.probabilityOfChordsInLabels.forEach(
function(_chords, difficulty){
    Object.keys(
classifier.probabilityOfChordsInLabels.get(difficulty)).forEach(
function(chord){
      classifier.probabilityOfChordsInLabels.get(difficulty)[chord]
/= classifier.songs.length;
    });
  });
}

The problem is that when we assign one set to another, we aren’t just copying the values from the Set object on the righthand side of the assignment into the Set object on the lefthand side. Both classifier.probabilityOfChordsInLabels and classifier.chordCountsInLabels are just fingers pointing at the same object. If you change the values of the set by referencing either name, both will be affected.

Here is a short example to demonstrate this:

x = {a: 2};
// returns { a: 2 }
y = x;
// returns { a: 2 }
x['b'] = 3;
// returns 3
y;
// returns { a: 2, b: 3 }
y['c'] = 5;
// returns 5
x;
// returns { a: 2, b: 3, c: 5 }

However, these all involve what happens when you update an object. If you reassign the object again, it will not change both labels to be pointing at the new object:

x = {a: 2};
// returns { a: 2 }
y = x;
// returns { a: 2 }
x = {b: 5};
console.log(y);
// prints { a: 2 }
// because y still ponts at the original object
// x has been assigned to a new object

Back to our code, if probabilityOfChordsInLabels and chordCountsInLabels do the same thing, we can just replace references to the former with the latter:

function setProbabilityOfChordsInLabels(){
  classifier.chordCountsInLabels = classifier.chordCountsInLabels;
  classifier.chordCountsInLabels.forEach(function(_chords, difficulty){
    Object.keys(classifier.chordCountsInLabels.get(difficulty))
      .forEach(function(chord){
        classifier.chordCountsInLabels.get(difficulty)[chord]
/= classifier.songs.length;
    });
  });
}

Now line two is looking more obviously redundant, which is great, because we know we can delete it:

function setProbabilityOfChordsInLabels(){
  classifier.chordCountsInLabels.forEach(function(_chords, difficulty){
    Object.keys(classifier.chordCountsInLabels.get(difficulty))
      .forEach(function(chord){
        classifier.chordCountsInLabels.get(difficulty)[chord]
/= classifier.songs.length;
    });
  });
}

We also have two more references to probabilityOfChordsInLabels to change inside of classifier . One is this line, which we can delete:

probabilityOfChordsInLabels: new Map(),

The other is the last line in the following snippet:

const classifier = {
...
const value = 
this.probabilityOfChordsInLabels.get(difficulty)[chord];

The assignment to value (inside of the valueForChordDifficulty function of classifier ) should be updated to use chordCountsInLabels instead.

This leaves us with the following:

const classifier = {
...
const value = this.chordCountsInLabels.get(difficulty)[chord];

And tests should be passing at this point. In some cases, the correct refactoring here would be to truly copy the Set object into a new one. Then, both would be independent objects. We don’t actually need two objects, though, so we’ll try a different approach here.

“Copying” Objects

If you’re interested in copying objects in JavaScript, look into the terms deep copy versus shallow copy , as well as cloning and the Object functions freeze , assign , and seal . They might do what you want.  Or maybe you want to create a new object tied to the old one’s prototype with Object.create . Maybe you want a totally new object with Object.assign . Maybe you want to make a constructor function or a class? Maybe you just want a factory function (see Chapter 8 ). Maybe you want a new and immutable container for your data.

By the way, there are two things to note about Object.create . First, it doesn’t own the properties from the prototype object (its first parameter), so they could possibly be overwritten. Second, it only “copies” enumerable properties, so don’t expect it to copy everything .

There are about a million and five ways to do inheritance and copying objects in JavaScript. That makes it hard to pick one. The point here is to remember that assigning with = is not one of them. 

Since the last code sample contains our only reference to the value of the new object, all we have now is an object that changes. But maybe we don’t need to update the object at all. Let’s try using a function as an attribute, instead of a set that stores all of the values.

First, let’s move the setProbabilityOfChordsInLabels function into the classifier object:

const classifier = {
...
  setProbabilityOfChordsInLabels: function(){
    classifier.chordCountsInLabels
.forEach(function(_chords, difficulty){
      Object.keys(classifier.chordCountsInLabels.get(difficulty))
        .forEach(function(chord){
          classifier.chordCountsInLabels.get(difficulty)[chord]
  /= classifier.songs.length;
      });
    });
  },
  valueForChordDifficulty(difficulty, chord){
...

And we’ll also need to update our setLabelsAndProbabilities function to use classifier. ahead of the function call:

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  setChordCountsInLabels();
  classifier.setProbabilityOfChordsInLabels();
};

Running the test suite shows everything is working properly. Now let’s replace the references to classifier with this :

  setProbabilityOfChordsInLabels: function(){
    this.chordCountsInLabels.forEach(function(_chords, difficulty){
      Object.keys(this.chordCountsInLabels.get(difficulty))
        .forEach(function(chord){
          this.chordCountsInLabels.get(difficulty)[chord]
  /= this.songs.length;
      }, this);
    }, this);
  },

Recall that in addition to replacing classifier with this , we also need to pass this in as the optional second argument to both forEach calls.  Otherwise, our this context would get lost.  From earlier, we know that we could accomplish the same thing with arrow functions, but we’ll actually be removing this function soon, so we’ll avoid that refactoring for now.

Now we get to the crux of the problem: we don’t really want functions that set values through side effects. We want functions that return values. They are much easier to work with and keep track of. We won’t get all the way there in this chapter, and arguably, OOP fights that ethos, whereas FP encourages it (see Chapter 11 ).

As for setProbabilityOfChordsInLabels , all that looping amounts to very little. Really, all we want to do is divide the number of times the chord appears in a given difficulty by the number of songs.

You can delete the  setProbabilityOfChordsInLabels function from the object as well as its call (from inside of setLabelsAndProbabilities ). In its place, we’ll be using a simple function to check a given chord and difficulty combo. Add the following likelihoodFromChord function and update the valueForChordDifficulty function in classifier as follows:

const classifier = {
...
  likelihoodFromChord: function(difficulty, chord){
    return this.chordCountsInLabels
      .get(difficulty)[chord] / this.songs.length;
  },
  valueForChordDifficulty(difficulty, chord){
    const value = this.likelihoodFromChord(difficulty, chord);
    return value ? value + this.smoothing : 1;
  },
...

Now setLabelsAndProbabilities should look like this:

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  setChordCountsInLabels();
};

With these changes, we’ve simplified the code and stopped relying on as many reassignments .

At this point, all the tests should be working again. Just to recap what happened in this section, we had two variable names that were assigned to the same object. First, we changed all the instances of the second variable name to be the first variable name, leaving us with a variable that was updated. Then, instead of relying on the updates to that variable, we changed references to it to use a calculation to get the information (instead of just accessing where the information was stored).

About Reassigning Variables

Among the most important recent developments in JavaScript and beyond is the increased importance of functional programming. We’ll explore the benefits more in Chapter 11 , but one of the best things about it is how it allows for values to be easily trusted.

On the other end of the spectrum is reassigning values. Nothing makes a program harder to debug, write features for, refactor, or understand than broadly scoped variables that are assigned and reassigned. However, even variables that are fairly limited in scope can create maintenance difficulties when they are reassigned multiple times (e.g., a variable that changes a few times in just a 20-line function).

If there’s one thing that everyone could stop doing to benefit their code, it would be reassigning variables.

Updating values (adding/deleting/changing elements in an object or an array, for instance) can be just as bad, and is best done as a one-step operation (mostly simply through map , filter , or reduce ) behind a function and assigning to a new variable when possible. Overall, making the scope of most variables small should be a priority.

Something to consider is the idea that OOP encourages reassigning variables by having objects that stick around and allow properties to be changed.

Objects with Duplicate Information

In the last section, we dealt with two references to an object that was updated. Now, we’ll deal with two independent objects that are a bit too similar. classifier.songs and songList.songs seem to have almost identical data. Really, the only difference is the extra property ( name ) in songList.songs . Let’s get rid of classifier ’s songs property:

const classifier = {
...
likelihoodFromChord: function(difficulty, chord){
  return this.chordCountsInLabels
    .get(difficulty)[chord] / songList.songs.length;
},

We need to make two changes to classifier . Delete the songs attribute and change this to songList in the likelihoodFromChord function.

Next, we have to delete the second line of our train function:

function train(chords, label){
  classifier.songs.push({label: label, chords: chords}); // this one

Also, setLabelProbabilities should use songList.songs.length instead of classifier.songs.length :

function setLabelProbabilities(){
  classifier.labelCounts.forEach(function(_count, label){
    classifier.labelProbabilities.set(label, 
      classifier.labelCounts.get(label) / songList.songs.length);
  })
};

Last up, our setChordCountsInLabels function needs to be changed to use songList.songs instead of classifier.songs , and also to use song.difficulty rather than song.label :

function setChordCountsInLabels(){
  songList.songs.forEach(function(song){
    if(classifier.chordCountsInLabels.get(song.difficulty)
=== undefined){
      classifier.chordCountsInLabels.set(song.difficulty, {});
    }
    song.chords.forEach(function(chord){
      if(classifier.chordCountsInLabels.get(song.difficulty)[chord] >
0){
        classifier.chordCountsInLabels.get(song.difficulty)[chord] +=
1;
      } else {
        classifier.chordCountsInLabels.get(song.difficulty)[chord] =
1;
      }
    });
  });
}

At this point, the tests all should work again.

Bringing the Other Functions and Variables into classifier

Now, let’s move chordCountsInLabels into our classifier object:

const classifier = {
...
  setChordCountsInLabels = function(){
    songList.songs.forEach(function(song){
      if(classifier.chordCountsInLabels.get(song.difficulty)
  === undefined){
        classifier.chordCountsInLabels.set(song.difficulty, {});
      }
      song.chords.forEach(function(chord){
        if(classifier.chordCountsInLabels
.get(song.difficulty)[chord] > 0){
          classifier.chordCountsInLabels
.get(song.difficulty)[chord] += 1;
        } else {
          classifier.chordCountsInLabels
.get(song.difficulty)[chord] = 1;
        }
      });
    });
  },
...

And then we need to change the call in setLabelsAndProbabilities to reference it through the classifier :

function setLabelsAndProbabilities(){
  setLabelProbabilities();
  classifier.setChordCountsInLabels();
};

Next, we “ this -ify” the function by changing references to classifier to this and adding the thisArg to the forEach functions:

const classifier = {
...
  setChordCountsInLabels: function(){
    songList.songs.forEach(function(song){
      if(this.chordCountsInLabels.get(song.difficulty) === undefined){
        this.chordCountsInLabels.set(song.difficulty, {});
      }
      song.chords.forEach(function(chord){
        if(this.chordCountsInLabels.get(song.difficulty)[chord] > 0){
          this.chordCountsInLabels.get(song.difficulty)[chord] += 1;
        } else {
          this.chordCountsInLabels.get(song.difficulty)[chord] = 1;
        }
      }, this);
    }, this);
  },

All the tests still pass. Next, as with turning our likelihoodFromChord into a query rather than setting and later retrieving the values from the  probabilityOfChordsInLabels map, we can now do the same thing to eliminate the chordCountsInLabels map.

Take a look again at the setChordCountsInLabels function in the last snippet. All it does is loop through each chord in each song, and add 1 for every instance of the chord.

If all we have to do is count the number of times that a chord appears in a given difficulty, we can set up similar loops and a counter, and just add 1 when there is a match. Add this after setChordCountsInLabels in the classify object:

chordCountForDifficulty: function(difficulty, testChord){
  let counter = 0;
  songList.songs.forEach(function(song){
    if(song.difficulty === difficulty){
      song.chords.forEach(function(chord){
        if(chord === testChord){
          counter = counter + 1;
        }
      });
    }
  });
  return counter;
},

Now we can use that function instead of setting and retrieving the chord counts. Note that we don’t need thisArg s for our forEach functions because we don’t have any references to this anymore.

We need a few additional changes. First, the likelihoodFromChord function can be changed to:

likelihoodFromChord: function(difficulty, chord){
  return this.chordCountForDifficulty(difficulty, chord) /
songList.songs.length;
},

Next, we can delete our setChordCountsInLabels function from classifier , as well as the call to it in setLabelsAndProbabilities ,which leaves us with this:

function setLabelsAndProbabilities(){
  setLabelProbabilities();
};

This function now only exists to call another function. That means we can delete setLabelsAndProbabilities and just call setLabelProbabilities , which happens inside of the trainAll function. Change this:

function trainAll(){
  songList.songs.forEach(function(song){
    train(song.chords, song.difficulty);
  });
  setLabelsAndProbabilities();
};

to this:

function trainAll(){
  songList.songs.forEach(function(song){
    train(song.chords, song.difficulty);
  });
  setLabelProbabilities();
};

All the tests still pass. Before moving on, we should have another look at the chordCountForDifficulty function:

chordCountForDifficulty: function(difficulty, testChord){
  let counter = 0;
  songList.songs.forEach(function(song){
    if(song.difficulty === difficulty){
      song.chords.forEach(function(chord){
        if(chord === testChord){
          counter = counter + 1;
        }
      });
    }
  });
  return counter;
},

As we did in the classify function, when we have code that uses a loop to apply some function to a collection while altering a variable throughout, it is a good candidate for reduce . By the way, notice that we used let here, rather than const , because we have a variable that genuinely updates. Let’s change it to use reduce :

chordCountForDifficulty: function(difficulty, testChord){
  return songList.songs.reduce(function(counter, song){
    if(song.difficulty === difficulty){
      song.chords.forEach(function(chord){
        if(chord === testChord){
          counter = counter + 1;
        }
      });
    }
    return counter;
  }, 0);
},

We have a few changes here:

  • We return the result of reduce directly.
  • We replace our former counter variable   with a parameter to reduce ’s callback function.
  • We return the counter inside of the reduce function. Recognize that this is not returning from the chordCountForDifficulty function, but rather is used inside of reduce to set the counter value as it walks through the songList .

We can also use a filter , rather than a forEach , to help us count the elements meeting a condition. The filter function returns a new array consisting of elements that matched the conditional:

chordCountForDifficulty: function(difficulty, testChord){
  return songList.songs.reduce(function(counter, song){
    if(song.difficulty === difficulty){
      counter += song.chords.filter(function(chord){
        return chord === testChord;
      }).length;
    }
    return counter;
  }, 0);
},

We get the length of this array and add it to the counter . This means fewer updates to the counter . We also shaved two lines off of the chordCountForDifficulty function. We could have used a second reduce here instead of filter if we wanted to focus more on the count than the conditional, but that would mean an innerCount variable, which seems a bit clunkier.

Performance Impacts

The changes that we’ve made to query on an as-needed basis, rather than create structures more specific to later needs, are for refactoring purposes including reducing the size of the code.

Depending on the data access patterns of your program, this strategy might make your program execute slower or faster. Transforming structures into others that you’ll never use would be a waste. Transforming them into simpler (shallower) ones that will be accessed frequently could produce some performance benefit. All of this comes with the caveat that a given JavaScript platform might optimize your code in ways you don’t expect.  

We’ll discuss memoization along with functional programming in Chapter 11 . It, as well as other caching techniques, will help to overcome a performance hit you could take from the kind of refactoring we did here.

In any case, the approach of this book is to write for humans first, and worry about performance after the fact.

Moving on, we only have three functions left in the global scope: train , trainAll , and setLabelProbabilities . Those seem like they would fit right in as part of the classifier . Let’s move them now:

const classifier = {
...
trainAll: function(){
  songList.songs.forEach(function(song){
    classifier.train(song.chords, song.difficulty);
  });
  classifier.setLabelProbabilities();
},

train: function(chords, label){
  chords.forEach(chord => {
    classifier.allChords.add(chord);
  });
  if(Array.from(classifier.labelCounts.keys()).includes(label)){
    classifier.labelCounts.set(
      label, classifier.labelCounts.get(label) + 1);
  } else {
    classifier.labelCounts.set(label, 1);
  }
},

setLabelProbabilities: function(){
  classifier.labelCounts.forEach(function(_count, label){
    classifier.labelProbabilities.set(
      label, classifier.labelCounts.get(label) /
songList.songs.length);
  });
}
...

The biggest change is that we need to put these functions in the object attribute syntax. Additionally, trainAll needs to prepend its calls to train and setLabelProbabilities with classifier. .

Our call to trainAll in the tests also needs a new classifier. at the beginning:

classifier.trainAll();

The tests should be working at this point.

Now, let’s “ this -ify” our functions. That means changing instances of classifier to this as well as adding the thisArg as a second argument to the callbacks of the forEach functions inside of trainAll and setLabelProbabilities :

trainAll: function(){
  songList.songs.forEach(function(song){
    this.train(song.chords, song.difficulty);
  }, this);
  this.setLabelProbabilities();
},

train: function(chords, label){
  chords.forEach(chord => { this.allChords.add(chord) });
  if(Array.from(this.labelCounts.keys()).includes(label)){
    this.labelCounts.set(label, this.labelCounts.get(label) + 1);
  } else {
    this.labelCounts.set(label, 1);
  }
},

setLabelProbabilities: function(){
  this.labelCounts.forEach(function(_count, label){
    this.labelProbabilities.set(label, this.labelCounts.get(label) /
songList.songs.length);
  }, this);
}

Note that our forEach function inside of train doesn’t need a thisArg , because it uses the arrow syntax.

Now, everything is part of either classifier or songList . We’re down to two global variables. Now we can start to think about what belongs where a little more. One attribute of classifier sticks out as more appropriately being a part of songList : allChords .

We can simply move the attribute:

const songList = {
  allChords: new Set(),

Now we can delete it from classifier , and change this to songList in the function call inside of train :

chords.forEach(chord => { songList.allChords.add(chord) });

The tests should pass at this point.

Next, since we want our classifier to be the only point of global access in the program, we should move songList into it:

const classifier = {  
  songList: {
    allChords: new Set(),
    difficulties: ['easy', 'medium', 'hard'],
    songs: [],
    addSong: function(name, chords, difficulty){
      this.songs.push({name: name,
                      chords: chords,
                      difficulty: this.difficulties[difficulty]})
    }
  },
...

And now, there are a number of references to songList that need to be prepended with this. where they are inside of the classifier object. For those that are in the tests, they need to be prepended with classifier. . Do a search for “songList” and prepend as needed. Save, test, check, and commit.

Shorthand Syntax: Arrow, Object Function, and Object

Next up, let’s address some inconsistencies that we have in our function syntax. We’ve used arrow functions earlier in the book, but let’s go into a bit more detail here. We’ll start with an instance where we are using the arrow syntax already. In our train function we have the following:

train: function(){
  chords.forEach(chord => { this.songList.allChords.add(chord) });
...

We’ve discussed it a bit before, but what’s interesting about this is, well, this . We reference this inside of the anonymous function here and are free to not pass a thisArg ( this ) as the second parameter to forEach . As proof that this is something special with arrow functions and not code that happens to work fine without it, try converting it to the longhand form:

train: function(){
  chords.forEach(function(chord){
    this.songList.allChords.add(chord);
  });
...

It will break the tests! If you want to use that form, you need to include the this , as we currently do in trainAll :

train: function(){
  chords.forEach(function(chord){
    this.songList.allChords.add(chord);
  }, this);
...

But we could use bind on the function instead (we do this with reduce since it doesn’t have an option to pass a thisArg as a second parameter):

train: function(){
  chords.forEach(function(chord){
    this.songList.allChords.add(chord);
  }.bind(this));
...

Instead of doing either of those, let’s use the arrow syntax, which passes the this context to the inner function and saves us from having to type the word function so much. Awesome!

You might be wondering why we would ever not use the arrow syntax. There are a few cases. Most importantly, you wouldn’t want to use it in cases where the this you care about should not be the this that you have access to going into the function. For instance, you might expect the this of a click handler in jQuery to refer to the object clicked. If you use an arrow function, that won’t be the case.

Another reason is that in this form (ignoring the difficulty in passing parameters), the functions are easy to extract or inline, as the syntax is very similar to function declaration syntax:

// form 1

chords.forEach(function myFunction(){
  this.songList.allChords.add(chord);
}, this);

// form 2

chords.forEach(myFunction, this);

function myFunction(){
  this.songList.allChords.add(chord);
};

It’s easy to convert between these two forms. If you start with an anonymous function in form 1 (with or without arrow syntax), it takes a bit of extra work to convert it into a standalone, named function. But for all of our functions used with forEach , map , reduce , and filter , we can easily replace them with arrow functions. That shaves off about 10 lines of code. By the way, with our refactoring so far, what was once about 110 lines is now down to 63. It’s small enough to see the whole thing at once (minus the tests):

const classifier = {
  labelCounts: new Map(),
  labelProbabilities: new Map(),
  chordCountsInLabels: new Map(),
  smoothing: 1.01,
  songList: {
    allChords: new Set(),
    difficulties: ['easy', 'medium', 'hard'],
    songs: [],
    addSong: function(name, chords, difficulty){
      this.songs.push({name: name,
                      chords: chords,
                      difficulty: this.difficulties[difficulty]});
    }
  },
  chordCountForDifficulty: function(difficulty, testChord){
    return this.songList.songs.reduce((counter, song) => {
      if(song.difficulty === difficulty){
        counter += song.chords.filter((chord) => {
          return chord === testChord;
        }).length;
      }
      return counter;
    }, 0);
  },
  likelihoodFromChord: function(difficulty, chord){
    return this.chordCountForDifficulty(difficulty, chord) /
this.songList.songs.length;
  },
  valueForChordDifficulty(difficulty, chord){
    const value = this.likelihoodFromChord(difficulty, chord);
    return value ? value + this.smoothing : 1;
  },
  trainAll: function(){
    this.songList.songs.forEach((song) => {
      this.train(song.chords, song.difficulty);
    });
    this.setLabelProbabilities();
  },
  train: function(chords, label){
    chords.forEach(chord => { this.songList.allChords.add(chord) } );
    if(Array.from(this.labelCounts.keys()).includes(label)){
      this.labelCounts.set(label, this.labelCounts.get(label) + 1);
    } else {
      this.labelCounts.set(label, 1);
    }
  },
  setLabelProbabilities: function(){
    this.labelCounts.forEach((_count, label) => {
      this.labelProbabilities.set(label, this.labelCounts.get(label) /
this.songList.songs.length);
    });
  },
  classify: function(chords){
    return new Map(Array.from(
      this.labelProbabilities.entries()).map((labelWithProbability) => {
      const difficulty = labelWithProbability[0];
      return [difficulty, chords.reduce((total, chord) => {
        return total * this.valueForChordDifficulty(difficulty, chord);
      }, this.labelProbabilities.get(difficulty) + this.smoothing)];
    }));
  }
};

There are a few things to notice with the arrow syntax. First, if there is only one argument, it does not need to go in parentheses:

return new Map(Array.from(
  this.labelProbabilities.entries()).map(labelWithProbability => {

If there are two or more arguments, you’ll need them, as in this case:

setLabelProbabilities: function(){
  this.labelCounts.forEach((_count, label) =>{

One somewhat strange thing is that we also need parentheses if we have zero arguments. At this point, we can change all of our tests to use this syntax:

describe('the file', () => {
...
  it('classifies', () => {
...
  it('classifies again', () => {
...
  it('label probabilities', () => {
...

Moving on to function declaration shorthand syntax for objects, we could use the arrow syntax and declare our trainAll function like this:

trainAll: () => {
  this.songList.songs.forEach(song => { 
    this.train(song.chords, song.difficulty);
  });
  this.setLabelProbabilities();
},

However, this is not what we want. We actually want the this that we get with the function keyword used, because that this is the object ( classifier ), which is what our this inside of the function refers to. When we declare functions this way, we get the context outside of the object (the global object, assuming nonstrict mode). In any case, there is a better shorthand for function declarations, which we’ll get to shortly. Let’s put it back to this:

trainAll: function(){
  this.songList.songs.forEach(song => { 
    this.train(song.chords, song.difficulty);
  });
  this.setLabelProbabilities();
},

One other weird thing about the arrow syntax is that sometimes we use braces {} , and other times we don’t. Right now we have this:

counter += song.chords.filter((chord) => {
          return chord === testChord;
        }).length;

Let’s change that to this:

counter += song.chords.filter(chord => chord === testChord).length;

The lack of parentheses, braces, and the return might seem a little jarring because it makes the statement denser. There is an additional consideration with the braceless version, though: it implicitly returns the result of its execution. In the case of our last code snippet, that means it returns true or false .

Also note that because the brace syntax is used as a way to group the function body, if you want to return an object like this, you’ll be disappointed:

someFunction(someArg => {someThing: 'someValue'}) // nope

To return an object, you’ll need to add parentheses:

someFunction(someArg => ({someThing: 'someValue'})) // ok

As a matter of personal style, I would recommend going for less syntax when possible. That means this:

chords.forEach(chord => { this.songList.allChords.add(chord) } );

can become this:

chords.forEach(chord => this.songList.allChords.add(chord) );

During the discussion of arrow functions, we brushed up against the idea of a shorthand for declaring functions as part of an object. This is how we’re currently declaring most functions:

const classifier = {
...
    addSong: function(name, chords, difficulty){
...
  chordCountForDifficulty: function(difficulty, testChord){
...

However, we have one exception:

valueForChordDifficulty(difficulty, chord){

// instead of 

valueForChordDifficulty: function(difficulty, chord){

Using this shorthand syntax can completely remove the : function part, making the functions look like this:

const classifier = {
  songList: {
...
    addSong(name, chords, difficulty){
...
  chordCountForDifficulty(difficulty, testChord){
...

After doing that with all of our function declarations, we are actually completely free from the function keyword in this file! An incredible source of visual noise and extra typing is now gone. Thanks, ES2015!

Note, however, that this shorthand only works inside of object literals and classes. Outside of those contexts (in a normal function, global scope, or constructor function scope, for example), the interpreter will throw an error on the { .

Once again, we can see that our shorthand syntax is less portable than the longhand version.

Computed Properties

While we’re discussing function declaration shorthand, it’s worth noting that you could declare properties of an objec t dynamically, like this:

songs = {
  ['first' + 'Song']: {},
  ['second' + 'Song']: {},
  ['third' + 'Song']: {}
}

Basically, you can run JavaScript inside those square brackets to generate property names. This is a trivial example (and you’d probably want some data in your objects), but you might find this convenient at some point.

Be aware, however, that when dynamically defining labels of properties (or accessing them dynamically as in songs['first' + 'Song'] ), you lose your ability to easily search for simple strings like firstSong in your codebase.

The last bit of shorthand we could implement is in the addSong function. Right now we have this:

addSong(name, chords, difficulty){
  this.songs.push({name: name,
                   chords: chords,
                   difficulty: this.difficulties[difficulty]});
}

But we could shorten the object inside of push to use the object shorthand , like this:

this.songs.push({name, chords,
                 difficulty: this.difficulties[difficulty]});

Getting New Objects with Constructor Functions

Up to now, we’ve been dealing with object literals. We’ll get to classes in a bit, but first let’s explore another option: creating objects with constructor functions. To use these we would have to change our code to something like the following:

const Classifier = function(){
  const SongList = function() {
    this.allChords = new Set();
    this.difficulties = ['easy', 'medium', 'hard'];
    this.songs = [];
    this.addSong = function(name, chords, difficulty){
      this.songs.push({name,
                      chords,
                      difficulty: this.difficulties[difficulty]});
    };
  };
  this.songList = new SongList();
  this.labelCounts = new Map();
  this.labelProbabilities = new Map();
  this.chordCountsInLabels = new Map();
  this.smoothing = 1.01;
  this.chordCountForDifficulty = function(difficulty, testChord){
    return this.songList.songs.reduce((counter, song) => {
      if(song.difficulty === difficulty){
        counter += song.chords.filter(chord => chord === testChord).length;
      }
      return counter;
    }, 0);
  };
  this.likelihoodFromChord = function(difficulty, chord){
    return this.chordCountForDifficulty(difficulty, chord) /
this.songList.songs.length;
  };
  this.valueForChordDifficulty = function(difficulty, chord){
    const value = this.likelihoodFromChord(difficulty, chord);
    return value ? value + this.smoothing : 1;
  };
  this.trainAll = function(){
    this.songList.songs.forEach((song) => {
      this.train(song.chords, song.difficulty);
    });
    this.setLabelProbabilities();
  };
  this.train = function(chords, label){
    chords.forEach(chord => this.songList.allChords.add(chord) );
    if(Array.from(this.labelCounts.keys()).includes(label)){
      this.labelCounts.set(label, this.labelCounts.get(label) + 1);
    } else {
      this.labelCounts.set(label, 1);
    }
  };
  this.setLabelProbabilities = function(){
    this.labelCounts.forEach((_count, label) => {
      this.labelProbabilities.set(label, this.labelCounts.get(label) /
this.songList.songs.length);
    });
  };
  this.classify = function(chords){
    return new Map(Array.from(
      this.labelProbabilities.entries()).map((labelWithProbability) => {
      const difficulty = labelWithProbability[0];
      return [difficulty, chords.reduce((total, chord) => {
        return total * this.valueForChordDifficulty(difficulty, chord);
      }, this.labelProbabilities.get(difficulty) + this.smoothing)];
    }));
  };
};
const wish = require('wish');
describe('the file', () => {
  const classifier = new Classifier();
...

The tests only have a small change, because we need to initialize our classifier with:

const classifier = new Classifier();

That is how you instantiate an object in JavaScript using new with a constructor function. Notice that we are also instantiating a songList property in a similar way inside of the classifier :

this.songList = new SongList();

Most of our changes are to existing code, but the new Classifier() and new SongList() lines are, well, new.

Don’t forget to use new in constructor functions

If you forget new when calling a constructor function, your function may still run fine, but there’s a chance it won’t. This is because this will be bound to the global object (or undefined in strict mode).

Sometimes, this fear (what if people forget the new keyword!?) is cited as the main motivation behind preferring Object.create over new with a constructor function. The stronger case for Object.create has more to do with seeking consistency with and not obscuring JavaScript’s prototypal nature, rather than using the “pseudoclassical style” that constructor functions (and classes) with new promote.

On the more flexible side of things, the parentheses after the constructor call following new are optional when no arguments are passed to the function. It’s a bit weird, but these are the same:

this.songList = new SongList();
this.songList = new SongList;

There is an important difference between creating objects like this and using object literals. If you use an object literal, you are stuck doing some cloning/deep copying/ Object.create hijinks to get a new version. As we explored earlier, assigning something to a new variable using = just creates a new reference to the same object: two fingers pointing to the same moon. If you need more than one moon, you’re going to need new , Object.create , class , and/or some other copying/cloning utility. If you know that you’re going to want more than one object, object literals might not be the best starting point for creating them.

This snippet also demonstrates another result of this change: we have to add this. to all of our properties when we use a constructor function. Also notice that this syntax forces us to add our function keywords back in with the colons replaced with equal signs. Lastly, the commas at the end of statements have been replaced with semicolons (or not, in special cases, if you’re one of those people).

Speaking of semicolons...

Some people really hate semicolons. They’ll only use them when absolutely necessary, as evidence of their deep knowledge of JavaScript’s automatic semicolon insertion (ASI).

Personally, I find the edge cases for when semicolons are necessary somewhat hard to remember, and I feel that others (including people I work with) do too. For those reasons, I include them most of the time.

“To semicolon, or not to semicolon?” is not the ultimate question for a human: this is a job for a linter to handle.

Although the syntax might not be what we prefer, the tests still pass, so this is a successful refactoring so far. What have we gained? Well, because we’re inside of the constructor function and not constrained by the JSON syntax, we’re free to write any statements we want. That means we could have private (meaning unexposed) functions and variables inside of the constructor, as well as declaring global variables by not using var , let , or const (we could also do that in the object literal syntax, but not as directly). Most importantly, as mentioned before, we can get multiple instances of the same object quite simply with new , rather than going through somewhat unintuitive steps to “clone” or “copy” or “create” one.

Constructor Functions Versus Factory Functions

Let’s take a break from our classifier for just a minute. You might find this sample similar to the diary code from Chapter 5 , as it also concerns privacy. However, this discussion is focused more on objects and their creation.

We’ll be defining our API in a later section of this chapter, and in order to do that, we should be familiar with what we can and can’t access inside of constructor functions. The following code sample is a bit shorter, so it will be easier to understand this before applying the concepts to our NBC code:

// constructor function
const Secret = function(){
  this.normalInfo = 'this is normal';
  const secret = 'sekrit';
  const secretFunction = function(){
    return secret;
  };
  this.notSecret = function(){
    return secret;
  };
  totallyNotSecret = "I'm defined in the global scope";
};
const s = new Secret();
console.log(s.normalInfo); // 'this is normal'
console.log(s.secret); // undefined
console.log(s.secretFunction()); // error
console.log(s.notSecret()); // 'sekrit'
console.log(s.totallyNotSecret); // undefined
console.log(totallyNotSecret); // I'm defined in the global scope

An alternative to creating objects with the new keyword is using Object.create . Before we change our classifier, let’s just observe the differences between this construct and new , as in the last snippet:

// factory function
var secretTemplate = (function(){
  var obj = {};
  obj.normalInfo = 'this is normal';
  const secret = 'sekrit';
  const secretFunction = function(){
    return secret;
  };
  obj.notSecret = function(){
    return secret;
  };
  totallyNotSecret = "I'm defined in the global scope";
  return obj;
})();
const s = Object.create(secretTemplate);
console.log(s.normalInfo); // 'this is normal'
console.log(s.secret); // undefined
console.log(s.secretFunction()); // error
console.log(s.notSecret()); // 'sekrit'
console.log(s.totallyNotSecret); // undefined
console.log(totallyNotSecret); // "I'm defined in the global scope"

So, when we use Object.create , we need to supply an object to be patterned from. To retain the flexibility of using a constructor with new , we end up returning an object inside of the function. Note that this function is an IIFE. However, we could use a normal function expression as well:

var secretTemplate = function(){
...
};
const s = Object.create(secretTemplate());

This gives us the same object, but seems a bit less clear. Also, in this construction, the function will have to run every time we create a new object. In the IIFE version, the secretTemplate function only has to run once, and to create new objects we just reference the template object that was created.

Reordering our code a bit, we could express our object-returning code more concisely like this:

// module pattern
var secretTemplate = (function(){
  const secret = 'sekrit';
  const secretFunction = function(){
    return secret;
  };
  totallyNotSecret = "I'm defined in the global scope";
  return {normalInfo: 'this is normal',
          notSecret(){
            return secret;
          }};
})();
const s = Object.create(secretTemplate);
console.log(s.normalInfo); // 'this is normal'
console.log(s.secret); // undefined
console.log(s.secretFunction()); // error
console.log(s.notSecret()); // 'sekrit'
console.log(s.totallyNotSecret); // undefined
console.log(totallyNotSecret); // "I'm defined in the global scope"

This uses the module pattern , not to be confused with modules to import and export packages. A popular variation on the module pattern is the revealing module pattern , shown here:

// revealing module pattern
var secretTemplate = (function(){
  const secret = 'sekrit';
  const secretFunction = function(){
    return secret;
  };
  totallyNotSecret = "I'm defined in the global scope";
  const normalInfo = 'this is normal';
  const notSecret = function(){
    return secret;
  };
  return {normalInfo, notSecret};

})();
const s = Object.create(secretTemplate);
console.log(s.normalInfo); // 'this is normal'
console.log(s.secret); // undefined
console.log(s.secretFunction()); // error
console.log(s.notSecret()); // 'sekrit'
console.log(s.totallyNotSecret); // undefined
console.log(totallyNotSecret); // "I'm defined in the global scope"

This is a bit cleaner, as it makes the object that is returned very concise and readable.

One More Thing About IIFEs

We just used an IIFE as the right side of our assignment statement. In that case, the variable is likely a good candidate to export as a module.

In other cases, where an IIFE is used specifically to reduce the scope of the code inside, we can use a block instead. So this:

(function(){
// code we don't want outside of this scope
})();

becomes this:

{
// code we don't want outside of this scope
};

But if you try to use a block, meaning {} , on the right side of an assignment (as we did with an IIFE), it will be interpreted as an object and likely give an error. In those cases, you’re stuck with the IIFE.

Getting back to our classifier , how would we use Object.create for a factory function? It turns out to be very simple, and it relies on the object literal syntax much more than how we rearranged things to use new with the constructor functions in the last section:

const classifierTemplate = {
  songList: {
    allChords: new Set(),
...
const wish = require('wish');
describe('the file', () => {
  var classifier = Object.create(classifierTemplate);

To make this code work, we only need two changes from what we did with the object literal. First, we need to regard our initial object as a template , so we rename it classifierTemplate . Second, in our tests (which refer to classifier ), we create the classifier object by passing the template object to Object.create . Note that we are just using an object literal here, not a function or IIFE, because we don’t have anything that we care about being private at the moment.

In case you forgot what advantages a factory function with Object.create and a constructor function with new have over just using the object literal directly, the main one is that these are ways to create multiple classifier variables. The songList is a property of classifier , and as a nested object, a new version of it will be created for each classifier , even though it uses the object literal syntax. Object.create and new (along with classes and modules) are also your gateways to inheritance, which we’ll discuss in more depth in the next chapter.

A class for Our Classifier

Next, we’ll convert our code into a class. Note that neither of our objects is a good fit for Map because they both contain various attributes, including functions. So what do we need to change to classify our code? Not too much:

class Classifier {
  constructor(){
    this.songList = {
      allChords: new Set(),
      difficulties: ['easy', 'medium', 'hard'],
      songs: [],
      addSong(name, chords, difficulty){
        this.songs.push({name,
                        chords,
                        difficulty: this.difficulties[difficulty]});
      }
    };
    this.labelCounts = new Map();
    this.labelProbabilities = new Map();
    this.smoothing = 1.01;
  };
  chordCountForDifficulty(difficulty, testChord){
    return this.songList.songs.reduce((counter, song) => {
      if(song.difficulty === difficulty){
        counter += song.chords.filter(
          chord => chord === testChord
        ).length;
      }
      return counter;
    }, 0);
  };
...

The first line might look a bit like a function definition, and under the hood it is (although this is becoming less apparent as JS classes evolve), but it’s a special kind of function. And as with a function, we could also assign a class expression to a variable, like this:

const Classifier = class {

As for the other changes in our code, the most significant changes in adapting from the object literal syntax are (as when we used a constructor function) having semicolons instead of commas. Otherwise, our function definitions are the same. Properties that aren’t functions, however, can conveniently be defined inside of a constructor function and use the this. syntax  and semicolons at the end. The constructor function runs when a new object is created, and it is responsible for assigning properties .

The only other important change is how the constructor is called, which is identical to the new /constructor function pattern:

const classifier = new Classifier();

Recall from earlier that if you don’t have any arguments needed for the constructor, this will work fine without the parentheses:

const classifier = new Classifier;
Static Functions

One utility that classes offer is the ability to add static functions. These are useful if you have any functions that don’t require an instance to be useful. In our case, every function we have references this , a sure sign that none of them can be made static. If we wanted to be very aggressive and extract a static function (that only is responsible for division), we could try to turn our likelihoodFromChord from this:

likelihoodFromChord(difficulty, chord){
  return this.chordCountForDifficulty(difficulty, chord)
  / this.songList.songs.length;
};

into these:

likelihoodFromChord(difficulty, chord){
  return this.divide(this.chordCountForDifficulty(difficulty,
                                                  chord),
                     this.songList.songs.length);
};
divide(dividend, divisor){
  return dividend / divisor;
};

And since divide clearly has nothing to do with the function itself (which is apparent because there are no references to this ), we can make it static, and change the call to reflect the new container of the function (the class, rather than the instance):

likelihoodFromChord(difficulty, chord){
  return Classifier.divide(this.chordCountForDifficulty(difficulty, chord),
                           this.songList.songs.length);
};
static divide(dividend, divisor){
  return dividend / divisor;
};

This change is unnecessary, as / gets the job done just fine, but static functions are fairly easy to implement. Feel free to revert these changes.

But Aren’t Classes Bad?

“JavaScript doesn’t have real classes! They are just functions and prototypes and objects underneath! It’s a trick. Don’t fall for it! Its true nature is disguised by them!”

Or “JavaScript was only built in 10 days or something, right? It’s a mess underneath, and clinging to new syntax is our only hope to avoid thinking about the differences between .prototype , [[prototype]] , getPrototypeOf , and __proto__ .”

Alternatively, “Classes are fine and useful if they run on your platform and your team can understand them.”

Also, as more features are added to JavaScript classes (such as real private attributes, as discussed in Chapter 5 ), they are starting to look less like “syntactic sugar” and more like a unique construct. This doesn’t invalidate arguments of preferring object composition or functional programming over OOP, but it does weaken the “classes are nothing special” argument.

Choosing Our API

Now that our class appears to be in pretty good shape, it’s time to consider our API itself. In other words, if someone were importing our code as a module, what functions would be public (accessible to them), and which would be private? As we know from Chapter 5 , the private/public distinction is a bit complicated in JavaScript (as of this writing, “private” currently either means obscured or inaccessible, although this is likely to change), but nonetheless, we can determine the ideal now, even before realizing the distinction fully in a module. We’ll tackle that in the next section. For now, we’re just choosing what functions we definitely want to be accessible.  

There are three functions from classify that we need to be public:

  • constructor
  • trainAll
  • classify

Additionally, our addSong function from songList needs to be accessible. For convenience’s sake, let’s add a function to the classifier:

class Classifier  {
  constructor(){
...
  };
  addSong(name, chords, difficulty){
    this.songList.addSong(name, chords, difficulty);
  };
...

What about train?

Currently, our API relies on following the pattern of adding songs and then training them all at once. Unfortunately, because of the side effects we have, our code is not idempotent (a concept covered in Chapter 11 ). In other words, our functions are not “pure,” because of their side effects, and running them in a different order than specified (or multiple times) is not handled well.

Namely, train does not run setLabelProbabilities , and if setLabelProbabilities were tied to train instead of trainAll , our tests would break.

This is a problem we will not fix in this chapter, but there is an idempotent (and functional) version of this NBC in Chapter 11 .

Now we can call the function directly from the classifier, which means the calls in our tests like this:

classifier.songList.addSong('imagine', 
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], 0);
classifier.songList.addSong('somewhereOverTheRainbow',
['c', 'em', 'f', 'g', 'am'], 0);

can turn into this:

classifier.addSong('imagine', 
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], 0);
classifier.addSong('somewhereOverTheRainbow',
['c', 'em', 'f', 'g', 'am'], 0);

Additionally, since our function in the classifier has become pure delegation, we no longer need to be so specific about the parameters:

class Classifier  {
  constructor(){
...
  };
  addSong(...songParams){ // rest
    this.songList.addSong(...songParams); // spread
  };
...

The ...songParams in the function definition is known as rest parameter syntax , and using a similar style in a function call is known as using the spread operator . It’s hard to keep these terms straight, but Chris Deely, one of the technical reviewers of this book, suggested this mnemonic: rest is for “receiving,” spread is for “sending.” That works for me. (Thanks, Chris.)

The rest parameter syntax takes any arguments you give it and turns them into an array. The spread operator does the opposite, splitting the array you give it into individual arguments to pass to the function.

The reason this is a good pattern to apply in this situation is that we already have a function definition for addSong inside of songList . If we decided to change the function in terms of what arguments it accepts, it would be nice not to have to change this function as well. Using rest and spread here affords us that flexibility.

By the way, if we discovered that in actuality songList was doing all the work, and classifier was simply delegating every function to it, removing these delegation functions and letting the tests (or client code that uses our module) call the songList versions directly would be worth considering. Having just one object that clients interact with is nice for them, but if our delegation is adding sufficient bulk, we should rethink the design.

Time for a Little Privacy?

As we saw in Chapter 5 , if we want fake privacy in a class, we can just add an underscore ( _ ) in front of all of the properties we want to be private. This convention lets people using the API know that they’re in weird territory if they’re addressing these properties directly (sometimes the private/internal aspects of an API are referred to as the “plumbing” as opposed to the “porcelain”).

Hopefully, your editor has a way to easily rename things (find and replace across not just a file, but the whole project). These are the labels you should prepend an underscore to:

  • songList
  • labelCounts
  • labelProbabilities
  • smoothing
  • chordCountForDifficulty
  • likelihoodFromChord
  • valueForChordDifficulty
  • train
  • setLabelProbabilities

Now we have an extremely simple path to exporting our class as a module. Let’s split up our tests and main file to prove it. First, we have some changes to make to nb.js :

module.exports = class Classifier {
  constructor(){
    this._songList = {
      allChords: new Set(),
      difficulties: ['easy', 'medium', 'hard'],
      songs: [],
      addSong(name, chords, difficulty){
        this.songs.push({name,
                        chords,
                        difficulty: this.difficulties[difficulty]});
      }
    };
    this._labelCounts = new Map();
    this._labelProbabilities = new Map();
    this._smoothing = 1.01;
  };
  addSong(...songParams){
    this._songList.addSong(...songParams);
  };
...
  classify(chords){
    return new Map(Array.from(
      this._labelProbabilities.entries()).map(
(labelWithProbability) => {
      const difficulty = labelWithProbability[0];
      return [difficulty, chords.reduce((total, chord) => {
        return total * this._valueForChordDifficulty(difficulty,
 chord);
      }, this._labelProbabilities.get(difficulty) + this._smoothing)];
    }));
  }
};

We’ve only made two changes here. The first is that the first line now has this at the beginning:

module.exports =

The second is that we’re moving all of our testing to a separate file (in the same directory) called nb_test.js :

const Classifier = require('./nb.js');
const wish = require('wish');
describe('the file', () => {
  const classifier = new Classifier;
  classifier.addSong('imagine', 
['c', 'cmaj7', 'f', 'am', 'dm', 'g', 'e7'], 0);
...
  it('label probabilities', () => {
    wish(classifier._labelProbabilities.get('easy') ===
0.3333333333333333);
    wish(classifier._labelProbabilities.get('medium') ===
0.3333333333333333);
    wish(classifier._labelProbabilities.get('hard') ===
0.3333333333333333);
  });
});

We’ve only made one change to our tests, and it’s right up top. If you run mocha nb_test.js , you should have no failures. Awesome.

But do you want actual privacy? For now, you have a couple of options. The first is to go the “revealing module pattern” route, change the class back into a constructor function, and make some seriously hefty changes. Or, you could try some more convoluted and esoteric things with ES2015’s Symbol s (creating privacy through obscurity) or WeakMap s, or using an initialization function (which is basically designing your own form of the revealing module pattern).

If we honestly think about the trade-offs here, though, what are you gaining by doing something complex and nonstandard? You’re making more work for yourself and others who might work on your module. The code itself and the tests become more complex. Trading your ability to call tests for truly private, unaddressable functions seems like a nonstarter.

What are the risks of going the underscore route? A few extra characters here and there will make your code ugly? People will think you’re too dumb to use the latest and most confusing workarounds? People using your module will insist on calling those functions, even if for the uninitiated you indicated in your documentation that they shouldn’t?

If your program is already living in constructor function city, this is a tougher call, but if you’re using classes, adding underscores seems like the much easier solution.

All that said, it seems like private fields and methods could be headed our way soon. The spec is still in the works as of this writing, but the basic idea is that references to private functions and attributes would use a # instead of an _ , and be accessible only from inside the class definition. See Chapter 5 for an example of what it may look like.  

Adapting the Classifier to a New Problem Domain

And now for the last topic for this program: what if, instead of songs with chords, we’re working with learning vocabulary, and instead of “easy,” “medium,” and “hard,” we’re classifying a corpus of text as either “understood” or “not understood”?

Some people (both coders and noncoders), upon thinking about a potential abstraction like this, will jump to the general case right away. Think about abstracting a general NBC with the code from the beginning versus the code now. Personally, I recommend building two or three kinds of something (even something as small as a function) before insisting they are similar and attempting to abstract them.

Now that our code is in better shape and our program is fairly small, it’s easy enough to attempt adapting it to a new domain.

Mostly, all we have to do is rename a lot of objects:

module.exports = class Classifier {
  constructor(){
    this._textList = {
      allWords: new Set(),
      understood: ['yes', 'no'],
      texts: [],
      addText(name, words, comprehension){
        this.texts.push({name, words,
comprehension: this.understood[comprehension]});
      }
    };
    this._labelCounts = new Map();
    this._labelProbabilities = new Map();
    this._smoothing = 1.01;
  };
  addText(...textParams){
    this._textList.addText(...textParams);
  };
  _wordCountForComprehension(comprehension, testWord){
    return this._textList.texts.reduce((counter, text) => {
      if(text.comprehension === comprehension){
        counter += text.words.filter(
          word => word === testWord
        ).length;
      }
      return counter;
    }, 0);
  };

  _likelihoodFromWord(comprehension, word){
    return this._wordCountForComprehension(comprehension, word) /
this._textList.texts.length;
  };
  _valueForWordComprehension(comprehension, word){
    const value = this._likelihoodFromWord(comprehension, word);
    return value ? value + this._smoothing : 1;
  };
  trainAll(){
    this._textList.texts.forEach((text) => {
      this._train(text.words, text.comprehension);
    });
    this._setLabelProbabilities();
  };

  _train(words, label){
    words.forEach(word => this._textList.allWords.add(word) );
    if(Array.from(this._labelCounts.keys()).includes(label)){
      this._labelCounts.set(label, this._labelCounts.get(label) + 1);
    } else {
      this._labelCounts.set(label, 1);
    }
  };

  _setLabelProbabilities(){
    this._labelCounts.forEach((_count, label) => {
      this._labelProbabilities.set(label, 
this._labelCounts.get(label) / this._textList.texts.length);
    });
  };

  classify(words){
    return new Map(Array.from(
      this._labelProbabilities.entries()).map(
(labelWithProbability) => {
      const comprehension = labelWithProbability[0];
      return [comprehension, words.reduce((total, word) => {
        return total * this._valueForWordComprehension(comprehension,
word);
      }, this._labelProbabilities.get(comprehension) +
this._smoothing)];
    }));
  }
};

And here are the tests:

Classifier = require('./nb_new_domain.js');
const wish = require('wish');
describe('the file', () => {
  const classifier = new Classifier;
  classifier.addText('english text',
                     ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                      'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'],
                      0);
  classifier.addText('japanese text',
                     ['あ',     'い',    'う',     'え',     'お',
                       'か',     'き',    'く',    'け',    'こ'],
                       1);

  classifier.trainAll();
  it('classifies', () =>{
    const classified = classifier.classify(['お', 'は', 'よ', 'う', 'ご', 'ざ',
                                            'い', 'ま', 'す']);
    wish(classified.get('yes') === 1.51);
    wish(classified.get('no') === 5.19885601);
  });
  it('number of words', ()=>{
    wish(classifier._textList.allWords.size === 27);
  });

  it('label probabilities', ()=>{
    wish(classifier._labelProbabilities.get('yes') === 0.5);
    wish(classifier._labelProbabilities.get('no') === 0.5);
  });
});

Based on the earlier input, the tests show that the Japanese is likely to be incomprehensible to someone who classified the original training data. If we wanted to go further with this text classifier, we might be interested in processing the text more thoroughly. This could mean by character/letter, by word, by sentence, or getting deeper into the grammars of the target languages with techniques like stemming . Similarly, with the music version, we could have considered sequences of chords (transitions can be more difficult than the chords themselves). It’s also possible that a reader of both languages could have a different threshold of understanding for a specific vocabulary (e.g., parts of a motorcycle), rather than classifying everything in one language as incomprehensible.

Again (as we did with “easy,” “medium,” “hard”), we’re stopping one step before our classifier prints “yes/no” or “Japanese/English” (we could train for either scenario), so we just pick the category with the largest associated number. Feel free to add a test and implement that feature if you’re feeling ambitious.

While those are all features to add, our purpose in this chapter—improving the quality of the code—has been accomplished, so we’re all set. Check out Chapter 11 for a functional version of this code. 

Wrapping Up

In this chapter (and Chapter 6 ), we covered a huge range of general refactoring techniques. Throughout the rest of the book, we’ll be looking at more specialized styles based on the paradigms JavaScript provides, including object-oriented programming, functional programming, and asynchronous programming.