Skip to content

Instantly share code, notes, and snippets.

@originalhat
Created February 13, 2015 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save originalhat/040d8bcbf9c7d78babe7 to your computer and use it in GitHub Desktop.
Save originalhat/040d8bcbf9c7d78babe7 to your computer and use it in GitHub Desktop.
var ModifierGroup = (function() {
  function ModifierGroup(_params) {
    if (_params != undefined) {
      this.name            = _params.name;
      this.modifiers       = _params.modifiers;
      this.credit          = _params.credit;
      this.max             = _params.max;
      this.min             = _params.min != null ? _params.min : 0;
      this.maxPrice        = _params.maxPrice;
      this.remainingCredit = _params.credit || 0;
      this.quantityText    = getQuantityText(this.min, this.max);

      this.normalizeDefaults();
    }

    function getQuantityText(min, max) {
      if (min) {
        min = min.to_n();
      }

      if (max) {
        max = max.to_n();
      }

      if ((!min && !max) || (min === 0 && max === 0)) {
        return null;
      }

      if ((min && !max) || (min === max)) {
        return "Choose " + min;
      }

      if (max && (!min || min === 0)) {
        return "Choose up to " + max;
      }

      if (max && min) {
        return "Choose from " + min + " to " + max;
      }
    }
  }

  ModifierGroup.prototype.normalizeDefaults = function() {
    return _.map(this.modifiers, (function(_this) {
      return function(modifier) {
        if (_this.totalDefaultCount() < _this.min) {
          if (modifier["default"] !== 1) {
            return _this.enableModifier(modifier);
          }
        }
      };
    })(this));
  };

  ModifierGroup.prototype.totalDefaultCount = function() {
    return _.reduce(this.modifiers, (function(memo, num) {
      return memo + num["default"];
    }), 0);
  };

  ModifierGroup.prototype.enableModifier = function(modifier) {
    modifier["default"] = 1;
    return modifier.preSelected = true;
  };

  return ModifierGroup;

})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment