Condition

by Patrick von Lieres

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.min.js"></script>

JavaScript

(function() {
	'use strict';

	/**
	 * This heper class is kind like a simple property holder used to validate them against a
	 * provided object using a simple, chainable syntax.
	 *
	 * To create a condition pass a key (String) and a value to one of the creator functions (where, and, or).
	 * Values of type function will get resolved using the appropriate object value.
	 *
	 * Methods:
	 * Condition.where(String key, Function|? value) initial factory method. Returns new condition instance.
	 * Condition.and(String key, Function|? value) - Add a AND-condition. Returns condition instance.
	 * Condition.or(String key, Function|? value) - Add a OR-condition. Returns condition instance.
	 * Condition.isMatch(Object) - Check if the given conditions match the provided object. Returns boolean value.
	 *
	 * Example:
	 * ```
	 * // the object to check against:
	 * var obj = {
	 *  name: 'Object A',
	 *  props: {
	 *      propA: 'Property A',
	 *      propB: 'Property B'
	 *  }
	 * }
	 *
	 * // simple:
	 * Condition.where('name', 'Object A').isMatch(obj);
	 * // returns true
	 *
	 * // disjunction:
	 * Condition.where('name', 'Invalid name').or('props.propA', 'Property A').isMatch(obj);
	 * // returns true
	 *
	 * // conjunction
	 * Condition.where('name', 'Invalid name').and('props.propA', 'Property A').isMatch(obj);
	 * // returns false
	 *
	 * // function typed value
	 * Condition.where('name', function(a) { return a == 'Object A'; }).isMatch(obj);
	 * // returns true
	 * ```
	 */

	var _ = require('lodash');

	function Condition() {
		this.conditions = [];
	}

	function where(property, value) {
		var cond = new Condition();
		return cond.and(property, value);
	}

	Condition.prototype.addCondition = function(type, property, value) {
		this.conditions.push({
			type : type || 'and',
			property : property,
			value : value
		});
		return this;
	}

	Condition.prototype.and = function(property, value) {
		return this.addCondition('and', property,...