Skip to content

Commit

Permalink
Merge pull request #5 from drazik/fromjson-options
Browse files Browse the repository at this point in the history
feat: fromJson can take an object as parameter
  • Loading branch information
Wozacosta authored Mar 29, 2018
2 parents 1e3fe88 + 8c1c99d commit ecdd1bb
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lib/classificator.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,41 @@ const STATE_KEYS = (module.exports.STATE_KEYS = [
* Initializes a NaiveBayes instance from a JSON state representation.
* Use this with classifier.toJson().
*
* @param {String} jsonStr state representation obtained by classifier.toJson()
* @return {NaiveBayes} Classifier
* @param {String|Object} jsonStrOrObject state representation obtained by classifier.toJson()
* @return {NaiveBayes} Classifier
*/
module.exports.fromJson = jsonStr => {
let parsed;
module.exports.fromJson = jsonStrOrObject => {
let parameters;

try {
parsed = JSON.parse(jsonStr);
switch (typeof jsonStrOrObject) {
case 'string':
parameters = JSON.parse(jsonStrOrObject);
break;

case 'object':
parameters = jsonStrOrObject;
break;

default:
throw new Error('');
}
} catch (e) {
console.error(e);
throw new Error('Naivebayes.fromJson expects a valid JSON string.');
console.log(e);
throw new Error('Naivebays.fromJson expects a valid JSON string or an object.')
}

// init a new classifier
let classifier = new Naivebayes(parsed.options);
let classifier = new Naivebayes(parameters.options);

// override the classifier's state
STATE_KEYS.forEach(k => {
if (!parsed[k]) {
if (!parameters[k]) {
throw new Error(
`Naivebayes.fromJson: JSON string is missing an expected property: [${k}].`
);
}
classifier[k] = parsed[k];
classifier[k] = parameters[k];
});

return classifier;
Expand Down

0 comments on commit ecdd1bb

Please sign in to comment.