I have the following test case in a coding kata for javascript:
*word-count_test.js
var words = require('./word-count');
describe("words()", function() {
it("handles properties that exist on Object’s prototype", function() {
var expectedCounts = { reserved: 1, words : 1, like :1, prototype: 1, and : 1, toString: 1, "ok?": 1};
expect(words("reserved words like prototype and toString ok?")).toEqual(expectedCounts);
});
});
The following code will not pass this:
code v1
var words = function(phrase) {
var wordCountAry = {};
// split on whitespace, including newline
phrase.split(/\s/).forEach(function(oneWord) {
if (!wordCountAry[oneWord]) {
wordCountAry[oneWord] = 1;
} else {
wordCountAry[oneWord]++;
}
});
return wordCountAry;
};
module.exports = words;
But something like the following counter line will not trigger the error:
code v2
wordCountary[word] = (+wordCountary[word] || 0) + 1
So what is so special about that unary "+" operator?