hasValidFormStructure

by ParanoidAndroid77

JavaScript

function hasSameProps(validSource, wannaBe, strict) {
		
    //false when wannabe property is an array but validSource is not
    if (typeof validSource === 'object' && Array.isArray(wannaBe)) {
      return false;
    }

    //check for wannaBe overlapping props
    if (!Object.keys(wannaBe).every(function(key) {
        return validSource.hasOwnProperty(key);
      })) {
      // console.log('wannaBe has extra keys')
      return false;
    }

    //check every key for being same
    return Object.keys(validSource).every(function(key) {
      //if object
      if (typeof(validSource[key]) === 'object' && typeof(wannaBe[key]) === 'object') {

        //check array is array
        if (Array.isArray(validSource[key])) {
          //console.log('must be array key: ' + key);
          return Array.isArray(wannaBe[key]);
        } else {
          //recursively check nested object
          return hasSameProps(validSource[key], wannaBe[key]);
        }

      } else {

        //check every key is present in the wanna be object
        if (wannaBe[key] === undefined) {
          // console.log('wannaBe does not have key:' + key)
          return false;
        }


        //check the type of value is the same (not the actual value, which can be different)
        if (strict) {
          if (typeof validSource[key] !== typeof wannaBe[key]) {
            //console.log('wannaBe type is wrong for key: ' + key)
            return false;
          }
        }

        return true;
      }
    });
  }


hasValidFormStructure = function(form) {

  var validFormStructure = {
    data: {
      id: '',
      type: 'form',
      form: {
        ref: '',
        name: '',
        slug: '',
        type: 'hierarchy',
        inputs: []
      }
    }
  };

  //compare a valid object against the imported form object if they have the same keys
  if (!hasSameProps(validFormStructure, form)) {
    return false;
  }

  ////id must be string and not empty
  //if (typeof form.data.id !==...