Condition

by evgkch

JavaScript

const Types = {

  isFunc(target) {
    return target && typeof target === 'function';
  },

  isObject(target) {
    return typeof target === 'object' && !Array.isArray(target) && target !== null;
  },

  isPromise(target) {
    return target instanceof Promise;
  },

  isArray(target) {
    return typeof target === 'object' && Array.isArray(target);
  },

  isUndefined(target) {
    return typeof target === 'undefined';
  },

  isNull(target) {
    return typeof target === 'object' && !target;
  },

  isNullOrUndefined(target) {
    return Types.isNull(target) || Types.isUndefined(target);
  },

  isBool(target) {
    return target === true || target === false;
  },

  isString(target) {
    return typeof target === 'string';
  }

}

class Condition {

	static for(target) {
    if (Types.isArray(target))
    	return new Condition(target, 'check');
    else
    	throw new Error(`target must be an array but git ${typeof target}`);
  }
  
  static with(target) {
    if (Types.isArray(target))
    	return new Condition(target, 'equals');
    else
    	throw new Error(`target must be an array but git ${typeof target}`);
  }
  
  static and(a, b) {
  	if (a == undefined)
    	return b;
    else
  		return a && b;
  }
  
  static or(a, b) {
  	if (a == undefined)
    	return b;
    else
  		return a || b;
  }
  
  static check(condition) {
  	if (condition == 'every')
    	return Condition.and;
    if (condition == 'some')
    	return Condition.or;
    throw new Error();
  }
  
  static call(a, b, method) {
  	if (method == 'check')
    	return a(b);
    else if (method == 'equals')
    	return b(a);
    else
    	throw new Error();
  }
  
  get result() {
  	return this._result;
  }
  
  set result(res) {
  	this._result = res;
  }
  // g can be anything
  some(g) {
  	this._do(i => {
    	this.result = Condition.check('some')(
      	this.result,
        Condition.call(g, this.target[i], this.method)
      );
    })
    return this.result;
  }
  // g can be...