All files / lib flipr.js

100% Statements 24/24
100% Branches 4/4
100% Functions 10/10
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 644x 4x 4x   4x       39x       39x 1x   38x 38x         36x 3x   33x       1x       1x       1x       1x       32x 32x       2x 2x 4x             1x       4x  
const validateRule = require('./rules/validate-rule');
const getValueByRules = require('./rules/get-value-by-rules');
const idToPercent = require('./id-to-percent');
 
const defaultOptions = { rules: [] };
 
class Flipr {
  constructor(options) {
    this.options = {
      ...defaultOptions,
      ...options,
    };
    if (!this.options.source) {
      throw new Error('options.source is required');
    }
    this.source = this.options.source;
    this.options.rules.map(validateRule);
  }
 
  _getValue(config, key, input) {
    // value (static) always overrides values (dynamic) on config item
    if (Object.prototype.hasOwnProperty.call(config[key], 'value')) {
      return config[key].value;
    }
    return getValueByRules(input, this.options.rules, config[key].values);
  }
 
  static idToPercent(id) {
    return idToPercent(id);
  }
 
  static validateRules(rules) {
    rules.map(validateRule);
  }
 
  async preload() {
    await this.source.preload();
  }
 
  async flush() {
    await this.source.flush();
  }
 
  async getValue(key, input) {
    const config = await this.source.getConfig();
    return this._getValue(config, key, input);
  }
 
  async getConfig(input) {
    const config = await this.source.getConfig();
    const keys = Object.keys(config);
    return keys.reduce((memo, key) => ({
      ...memo,
      [key]: this._getValue(config, key, input),
    }), {});
  }
 
  async validateConfig() {
    return this.source.validateConfig(this.options.rules);
  }
}
 
module.exports = Flipr;