sijun.li | 9646230 | 2020-07-24 10:08:05 +0800 | [diff] [blame^] | 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 | /** |
| 24 | * This is just a simple version of deep copy |
| 25 | * Has a lot of edge cases bug |
| 26 | * If you want to use a perfect deep copy, use lodash's _.cloneDeep |
| 27 | * @param {Object} source |
| 28 | * @returns {Object} |
| 29 | */ |
| 30 | function deepClone(source) { |
| 31 | if (!source && typeof source !== 'object') { |
| 32 | throw new Error('error arguments', 'deepClone') |
| 33 | } |
| 34 | const targetObj = source.constructor === Array ? [] : {} |
| 35 | Object.keys(source).forEach(keys => { |
| 36 | if (source[keys] && typeof source[keys] === 'object') { |
| 37 | targetObj[keys] = deepClone(source[keys]) |
| 38 | } else { |
| 39 | targetObj[keys] = source[keys] |
| 40 | } |
| 41 | }) |
| 42 | return targetObj |
| 43 | } |
| 44 | |
| 45 | module.exports = { |
| 46 | param2Obj, |
| 47 | deepClone |
| 48 | } |