To learn the language of JavaScript, I did a dojo exercise by Roy Osherove. Is there a better way to organize this so that the only method exported is add
while keeping it in one single module?
module.exports = {
add: function (string) {
this._checkForError(string);
this._checkForNegatives(string);
return this._result(string);
},
_result: function (string) {
var numbers = this._numbers(string);
var result = numbers.reduce(function (sum, number) {
return sum + number;
});
return result;
},
_numbers: function (string) {
var modded = this._modded(string);
var numbers = modded.map(function (number) {
return parseInt(number, 10) || 0;
});
return numbers;
},
_checkForError: function (string) {
if (string.match(/\n$/)) {
throw 'Expression ending in newline!';
}
},
_negatives: function (string) {
var numbers = this._numbers (string);
var negatives = numbers.filter(function (number) {
return number < 0;
});
return negatives;
},
_delimiter: function (string) {
return (string.substr(0, 2) === '//') ? string[2] : ',';
},
_checkForNegatives: function (string) {
var negatives = this._negatives(string);
if (negatives.length > 0) {
throw 'Negatives not allowed: ' + negatives.join(', ');
}
},
_modded: function (string) {
var delimiter = this._delimiter(string);
return string.replace(/\n/, delimiter)
.split(delimiter);
}
};
module.exports
. It took me awhile to get my head around that. In this case, I can wrap the module in a function and at the end attach a return to the functionadd()
and define the remaining methods above to exclude it from being "exposed". @Dagg – Lucien Lachance Jun 2 at 15:20