util.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Get the first item that pass the test
  3. * by second argument function
  4. *
  5. * @param {Array} list
  6. * @param {Function} f
  7. * @return {*}
  8. */
  9. function find (list, f) {
  10. return list.filter(f)[0]
  11. }
  12. /**
  13. * Deep copy the given object considering circular structure.
  14. * This function caches all nested objects and its copies.
  15. * If it detects circular structure, use cached copy to avoid infinite loop.
  16. *
  17. * @param {*} obj
  18. * @param {Array<Object>} cache
  19. * @return {*}
  20. */
  21. export function deepCopy (obj, cache = []) {
  22. // just return if obj is immutable value
  23. if (obj === null || typeof obj !== 'object') {
  24. return obj
  25. }
  26. // if obj is hit, it is in circular structure
  27. const hit = find(cache, c => c.original === obj)
  28. if (hit) {
  29. return hit.copy
  30. }
  31. const copy = Array.isArray(obj) ? [] : {}
  32. // put the copy into cache at first
  33. // because we want to refer it in recursive deepCopy
  34. cache.push({
  35. original: obj,
  36. copy
  37. })
  38. Object.keys(obj).forEach(key => {
  39. copy[key] = deepCopy(obj[key], cache)
  40. })
  41. return copy
  42. }
  43. export function isObject (obj) {
  44. return obj !== null && typeof obj === 'object'
  45. }
  46. export function isPromise (val) {
  47. return val && typeof val.then === 'function'
  48. }
  49. export function assert (condition, msg) {
  50. if (!condition) throw new Error(`[vuex] ${msg}`)
  51. }