All files / src weightList.js

100% Statements 33/33
100% Branches 6/6
100% Functions 12/12
100% Lines 24/24
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 442140978x   3700401x   1x 7400805x   2x   500203x 1000405x 2x   1000403x     2x   1x   500204x 1x     500203x   500201x 3700401x 500201x 500201x     500201x   500200x 2140978x 2140978x 2140978x   500200x        
const selectOption = (arr, i) => ({ id: arr[i].id, item: arr[i].item });
 
const getProp = (arr, prop) => arr.map(opt => opt[prop]);
 
const checkProperty = (arr, prop) =>
  arr.every(item => Object.prototype.hasOwnProperty.call(item, prop));
 
const propErrorMsg = prop => `Every list item should have [${prop}] property`;
 
const checkProperties = (options, props) => props.map((prop) => {
  if (!checkProperty(options, prop)) {
    throw new TypeError(propErrorMsg(prop));
  }
  return true;
});
 
const throwTypeError = (msg) => { throw new TypeError(msg); };
 
const weightedList = (options) => {
 
  if (!Array.isArray(options)) {
    return throwTypeError('Weighted List expect Array of Objects as argument');
  }
 
  checkProperties(options, ['weight', 'item']);
 
  const weights = getProp(options, 'weight');
  const totalWeights = Number(weights.reduce((a, b) => a + b, 0).toPrecision(1));
  const num = Math.random();
  let set = 0;
  let selected;
 
  if (totalWeights !== 1) throwTypeError("Sum of 'weights' should be equal 1");
 
  weights.some((weight, i) => {
    set += weight;
    selected = selectOption(options, i);
    return num < set;
  });
  return selected;
};
 
export default weightedList;