all files / x-object/services/ Filter.js

100% Statements 14/14
100% Branches 4/4
100% Functions 6/6
100% Lines 10/10
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 44 45 46                                12×                                        
class Filter {
  constructor(object){
    this.object = object ;
  }
  execute(handler) {
    let switcher = {
      'string' : 'byKey',
      'array' : 'byKeys',
      'regexp': 'byRegExp',
      'function': 'byCallback'
    };
    if(handler && handler.constructor) {
      return this[switcher[handler.constructor.name.toLowerCase()]](handler);
    } else {
      return this.object;
    }
  }
 /**
  * @param {array} keys
  */
  byKeys( keys = []) {
    return keys.reduce((a, b) => {a[b]=this.object[b] ;return a},{});
 }
 
 /**
  * @param {string} key
  */
  byKey(key){
    return this.byKeys([key]);
 }
 /**
  * @param {RegExp} regxp
  */
  byRegExp(regxp){
    return this.byKeys(Object.keys(this.object).filter(k=>regxp.test(k) ))
  }
  /**
   * @param {function} callback
   */
  byCallback(callback){
    return this.byKeys(Object.keys(this.object).filter(k=>callback(k,this.object[k]) ))
  }
}
 
module.exports = Filter;