Code coverage report for src/schema/schemautil.js

Statements: 92.59% (50 / 54)      Branches: 91.11% (41 / 45)      Functions: 83.33% (5 / 6)      Lines: 92.59% (50 / 54)      Ignored: none     

All files » src/schema/ » schemautil.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87    1     1 5     1         1 19317 19317   19317 8812 8812 10505 2582 2582 19227 19227 10682     2582 7923 1   7922       1 8 8 19 19   19 15 5 5 4 10 10       8     1 104 104 209   104       1 860       860 2001     2001 38   1963 1312 651 290   361     860  
'use strict';
 
var schemautil = module.exports = {},
  util = require('../util');
 
var isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
};
 
schemautil.extend = function(instance, schema) {
  return schemautil.merge(schemautil.instantiate(schema), instance);
};
 
// instantiate a schema
schemautil.instantiate = function(schema) {
  var val;
  Iif (schema === undefined) {
    return undefined;
  } else if ('default' in schema) {
    val = schema.default;
    return util.isObject(val) ? util.duplicate(val) : val;
  } else if (schema.type === 'object') {
    var instance = {};
    for (var name in schema.properties) {
      val = schemautil.instantiate(schema.properties[name]);
      if (val !== undefined) {
        instance[name] = val;
      }
    }
    return instance;
  } else if (schema.type === 'array') {
    return [];
  }
  return undefined;
};
 
// remove all defaults from an instance
schemautil.subtract = function(instance, defaults) {
  var changes = {};
  for (var prop in instance) {
    var def = defaults[prop];
    var ins = instance[prop];
    // Note: does not properly subtract arrays
    if (!defaults || def !== ins) {
      if (typeof ins === 'object' && !util.isArray(ins) && def) {
        var c = schemautil.subtract(ins, def);
        if (!isEmpty(c))
          changes[prop] = c;
      } else Eif (!util.isArray(ins) || ins.length > 0) {
        changes[prop] = ins;
      }
    }
  }
  return changes;
};
 
schemautil.merge = function(/*dest*, src0, src1, ...*/){
  var dest = arguments[0];
  for (var i=1 ; i<arguments.length; i++) {
    dest = merge(dest, arguments[i]);
  }
  return dest;
};
 
// recursively merges src into dest
function merge(dest, src) {
  Iif (typeof src !== 'object' || src === null) {
    return dest;
  }
 
  for (var p in src) {
    Iif (!src.hasOwnProperty(p)) {
      continue;
    }
    if (src[p] === undefined) {
      continue;
    }
    if (typeof src[p] !== 'object' || src[p] === null) {
      dest[p] = src[p];
    } else if (typeof dest[p] !== 'object' || dest[p] === null) {
      dest[p] = merge(src[p].constructor === Array ? [] : {}, src[p]);
    } else {
      merge(dest[p], src[p]);
    }
  }
  return dest;
}