utils.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @param {string} url
  3. * @returns {Object}
  4. */
  5. function param2Obj(url) {
  6. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  7. if (!search) {
  8. return {}
  9. }
  10. const obj = {}
  11. const searchArr = search.split('&')
  12. searchArr.forEach(v => {
  13. const index = v.indexOf('=')
  14. if (index !== -1) {
  15. const name = v.substring(0, index)
  16. const val = v.substring(index + 1, v.length)
  17. obj[name] = val
  18. }
  19. })
  20. return obj
  21. }
  22. /**
  23. * This is just a simple version of deep copy
  24. * Has a lot of edge cases bug
  25. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  26. * @param {Object} source
  27. * @returns {Object}
  28. */
  29. function deepClone(source) {
  30. if (!source && typeof source !== 'object') {
  31. throw new Error('error arguments', 'deepClone')
  32. }
  33. const targetObj = source.constructor === Array ? [] : {}
  34. Object.keys(source).forEach(keys => {
  35. if (source[keys] && typeof source[keys] === 'object') {
  36. targetObj[keys] = deepClone(source[keys])
  37. } else {
  38. targetObj[keys] = source[keys]
  39. }
  40. })
  41. return targetObj
  42. }
  43. module.exports = {
  44. param2Obj,
  45. deepClone
  46. }