All files / src Object.js

100% Statements 15/15
100% Branches 8/8
100% Functions 11/11
100% Lines 15/15
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          112x       4x 8x 8x   4x   45x       56x 24x 12x           1x 1x   12x       28x 12x           2x  
import { BaseType, coerce } from './base';
import nativeTypeMap from './nativeTypeMap';
 
export default class ObjectType extends BaseType {
  static isOfType(val) {
    return typeof val === 'object' && !Array.isArray(val) && val !== null;
  }
 
  static withDefinition(definition) {
    const coercedDefinition = Object.keys(definition).reduce((o, key) => {
      o[key] = coerce(definition[key]);
      return o;
    }, {});
    return class ObjectWithDefinition extends this {
      static get properties() {
        return coercedDefinition;
      }
 
      static isOfType(val) {
        return super.isOfType(val)
          && Object.keys(definition).every((key) => this.properties[key].isOfType(val[key]))
          && Object.keys(val).every(key => !!this.properties[key]);
      }
    };
  }
 
  static keyValuePair(valueType) {
    const coercedValueType = coerce(valueType);
    return class ObjectKeyValuePair extends this {
      static get valueType() {
        return coercedValueType;
      }
 
      static isOfType(val) {
        return super.isOfType(val)
          && Object.keys(val).every(key => this.valueType.isOfType(val[key]));
      }
    }
  }
}
 
nativeTypeMap.set(Object, ObjectType);