cow-value-model.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  6. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  7. function copyWith(obj, key, value) {
  8. var result = typeof key === 'number' ? [].concat(_toConsumableArray(obj)) : _extends({}, obj);
  9. result[key] = value;
  10. return result;
  11. }
  12. var cowValueModel = exports.cowValueModel = function cowValueModel() {
  13. for (var _len = arguments.length, keyDescriptions = Array(_len), _key = 0; _key < _len; _key++) {
  14. keyDescriptions[_key] = arguments[_key];
  15. }
  16. var keys = [];
  17. keyDescriptions.forEach(function (each) {
  18. if (typeof each === 'number') keys.push(each);else keys.push.apply(keys, _toConsumableArray(each.toString().split('.')));
  19. });
  20. function setField() {
  21. var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  22. var index = arguments[1];
  23. var val = arguments[2];
  24. if (index >= keys.length) return val;
  25. var key = keys[index],
  26. value = x[key],
  27. modified = setField(value, index + 1, val);
  28. return value === modified ? x : copyWith(x, key, modified);
  29. }
  30. var GET_SENTINEL = {};
  31. return function (obj) {
  32. var val = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : GET_SENTINEL;
  33. return val === GET_SENTINEL ? keys.reduce(function () {
  34. var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  35. var key = arguments[1];
  36. return x[key];
  37. }, obj) : setField(obj, 0, val);
  38. };
  39. };