valueUtil.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. import { toArray } from './typeUtil';
  3. import get from '../../vc-util/get';
  4. import set from '../../vc-util/set';
  5. /**
  6. * Convert name to internal supported format.
  7. * This function should keep since we still thinking if need support like `a.b.c` format.
  8. * 'a' => ['a']
  9. * 123 => [123]
  10. * ['a', 123] => ['a', 123]
  11. */
  12. export function getNamePath(path) {
  13. return toArray(path);
  14. }
  15. export function getValue(store, namePath) {
  16. const value = get(store, namePath);
  17. return value;
  18. }
  19. export function setValue(store, namePath, value) {
  20. let removeIfUndefined = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  21. const newStore = set(store, namePath, value, removeIfUndefined);
  22. return newStore;
  23. }
  24. export function containsNamePath(namePathList, namePath) {
  25. return namePathList && namePathList.some(path => matchNamePath(path, namePath));
  26. }
  27. function isObject(obj) {
  28. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;
  29. }
  30. /**
  31. * Copy values into store and return a new values object
  32. * ({ a: 1, b: { c: 2 } }, { a: 4, b: { d: 5 } }) => { a: 4, b: { c: 2, d: 5 } }
  33. */
  34. function internalSetValues(store, values) {
  35. const newStore = Array.isArray(store) ? [...store] : _extends({}, store);
  36. if (!values) {
  37. return newStore;
  38. }
  39. Object.keys(values).forEach(key => {
  40. const prevValue = newStore[key];
  41. const value = values[key];
  42. // If both are object (but target is not array), we use recursion to set deep value
  43. const recursive = isObject(prevValue) && isObject(value);
  44. newStore[key] = recursive ? internalSetValues(prevValue, value || {}) : value;
  45. });
  46. return newStore;
  47. }
  48. export function setValues(store) {
  49. for (var _len = arguments.length, restValues = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  50. restValues[_key - 1] = arguments[_key];
  51. }
  52. return restValues.reduce((current, newStore) => internalSetValues(current, newStore), store);
  53. }
  54. export function cloneByNamePathList(store, namePathList) {
  55. let newStore = {};
  56. namePathList.forEach(namePath => {
  57. const value = getValue(store, namePath);
  58. newStore = setValue(newStore, namePath, value);
  59. });
  60. return newStore;
  61. }
  62. export function matchNamePath(namePath, changedNamePath) {
  63. if (!namePath || !changedNamePath || namePath.length !== changedNamePath.length) {
  64. return false;
  65. }
  66. return namePath.every((nameUnit, i) => changedNamePath[i] === nameUnit);
  67. }