all files / Enum.js/ index.js

79.17% Statements 19/24
58.82% Branches 10/17
83.33% Functions 5/6
79.17% Lines 19/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 44 45 46 47          24× 24×                                              
/* global define, __DEV__ */
 
(function () {
  'use strict';
 
  function Enum(dfn) {
    const props = {};
    const vals = [];
    Object.entries(dfn).forEach(([key, value]) => {
      props[key] = {value};
      vals.push(value);
    });
    return Object.freeze(
      Object.create(vals, props)
    );
  }
 
  Enum.coalesce = function(obj, field) {
    if (field in obj || field in Object.values(obj)) {
      return field;
    }
    return null;
  };
  Enum.enforce = function(obj, field) {
    var value = Enum.coalesce(obj, field);
    if (value !== null) {
      return value;
    }
    Iif (__DEV__) {
      throw new Error('Value ' + field + ' not found in object ' + obj);
    } else {
      throw new Error('Invalid Enum');
    }
  };
 
  Eif (typeof module !== 'undefined' && module.exports) {
    module.exports = Enum;
  } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
    // same as npm pacakge name
    define('enumjs', [], function () {
      return Enum;
    });
  } else {
    window.Enum = Enum;
  }
}());