API Docs for:
Show:

File: development/js/utils/conforms.js

import object from './object';
import type from './type';


/**
 * Helper to test if a instance implements a certain interface
 *
 * @module Utils
 * @class Utils.Conforms
 * @static
 */



/**
 * Accepts two objects, of which the first one defines the shape the second object 
 *     must be conform to. The conforms() function is especially useful if you
 *     have a function which only accepts a certain kind of input object (for
 *     example: a Gallery accepts only GalleryItems) to ensure the input has a
 *     matching interface
 *
 * @method conforms
 * @for Utils.Conforms
 * @param {object} iDescriptor Key-Value pairs describing the interface
 * @param {object} instance The instance to check for conformity
 * @return {boolean} True if conform, false if not
 *
 * @example
 *    import {conforms} from './utils/conforms';
 *    import {isString, isFunction} from './utils/type';
 * 
 *    var iDesc = {
 *        name: isString,
 *        sayHi: isFunction
 *    };
 *
 *    var testeeA = {
 *        name: 'John Doe',
 *        sayHi: function () { return 'Hi, I am ' + this.name; }
 *    };
 *
 *     var testeeB = {
 *        name: null,
 *        sayHi: true
 *    };
 *
 *
 *     conforms(iDesc, testeeA); // -> true
 *     conforms(iDesc, testeeB); // -> false
 *
 *
 *     // optional alternative, produces a function which only awaits the
 *     //   object to test
 *     var conformsIDesc = conforms(iDesc);
 *
 *     conformsIDesc(testeeA);
 *     // -> true
 */
export const conforms = (iDescriptor, instance) => {
    if (instance === undefined) {
        return (target) => {
            return conforms(iDescriptor, target);
        }
    }

    return object.keys(iDescriptor).every((key) => {
        return type.isFunction(iDescriptor[key]) &&
            !!iDescriptor[key](instance[key]);
    });
}



export default conforms;