all files / addon/validators/ sometimes.js

96.15% Statements 25/26
80% Branches 12/15
100% Functions 4/4
96.15% Lines 25/26
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    15× 13× 13×       28× 57×   48× 22× 22×         18× 18× 18×   18× 18×       18×     26× 20×           57× 25×   32×          
import { get } from '@ember/object';
 
export default function validateSometimes(validator, condition) {
  if (Array.isArray(arguments[0])) {
    let validators = arguments[0];
    return validators.map(guardValidatorWithCondition);
  } else {
    let validator = arguments[0];
    return guardValidatorWithCondition(validator);
  }
 
  function guardValidatorWithCondition(validator) {
    return function(key, newValue, oldValue, changes, content) {
      let thisValue = {
        get(property) {
          if (property.includes('.')) {
            let changesValue = get(changes, property);
            if (typeof changesValue !== 'undefined') {
              return changesValue;
            }
 
            // Check if the `changes` value is explicitly undefined,
            // or if it's not present at all.
            let pathSegments = property.split('.');
            let propName = pathSegments.pop();
            let objPath = pathSegments.join('.');
 
            let obj = get(changes, objPath);
            Iif (obj && obj.hasOwnProperty && obj.hasOwnProperty(propName)) {
              return changesValue;
            }
 
            return get(content, property);
          }
 
          if (changes.hasOwnProperty(property)) {
            return get(changes, property);
          } else {
            return get(content, property);
          }
        }
      };
 
      if (condition.call(thisValue, changes, content)) {
        return validator(key, newValue, oldValue, changes, content);
      }
      return true;
    };
  }
}