constraints/oroperator.js

'use strict';

/**
 * @author schukai GmbH
 */

import {Monster, AbstractOperator} from "./abstractoperator.js";

/**
 * The OrOperator is used to link several constraints. The constraint is fulfilled if one of the constraints is fulfilled.
 *
 * ```
 * <script type="module">
 * import {Monster} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.5.0/dist/modules/constraint/oroperator.js';
 * new Monster.Constraint.OrOperator(new Monster.Constraint.Valid(), new Monster.Constraint.Valid()).then(()=>console.log(true)).catch(()=>console.log(false));
 * </script>
 * ```
 *
 * Alternatively, you can also integrate this function individually.
 *
 * ```
 * <script type="module">
 * import {Valid} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.5.0/dist/modules/constraint/valid.js';
 * import {AndOperator} from 'https://cdn.jsdelivr.net/npm/@schukai/monster@1.5.0/dist/modules/constraint/oroperator.js';
 * new OrOperator(new Valid(), new Valid()).then(()=>console.log(true)).catch(()=>console.log(false));
 * </script>
 * ```
 *
 * @since 1.3.0
 * @copyright schukai GmbH
 * @memberOf Monster/Constraints
 */
class OrOperator extends AbstractOperator {

    /**
     * this method return a promise containing the result of the check.
     *
     * @param {*} value
     * @returns {Promise}
     */
    isValid(value) {
        var self = this;

        return new Promise(function (resolve, reject) {
            let a, b;

            self.operantA.isValid(value)
                .then(function () {
                    resolve();
                }).catch(function () {
                a = false;
                /** b has already been evaluated and was not true */
                if (b === false) {
                    reject();
                }
            });

            self.operantB.isValid(value)
                .then(function () {
                    resolve();
                }).catch(function () {
                b = false;
                /** b has already been evaluated and was not true */
                if (a === false) {
                    reject();
                }
            });
        });
    }


}

Monster.assignToNamespace('Monster.Constraints', OrOperator);
export {Monster, OrOperator}