/** * Created by clay on 2019/10/14 * Description: common utils */ /** * This is just a simple version of deep copy * Has a lot of edge cases bug * If you want to use a perfect deep copy, use lodash's _.cloneDeep * @param {Object} source * @returns {Object} targetObj */ const deepClone = function(source) { if (!source && typeof source !== 'object') { throw new Error('error arguments: deepClone') } let targetObj = source.constructor === Array ? [] : {} Object.keys(source).forEach(key => { if (source[key] && typeof source[key] === 'object') { targetObj[key] = deepClone(source[key]) } else { targetObj[key] = source[key] } }) return targetObj } /** * Randomly extract one or more elements from an array * If you want to use a perfect solution, use lodash's _.sample or _.sampleSize * @param {Array} arr * @param {number} count * @returns {Array} arr */ const getRandomArrayElements = function(arr, count = 1) { if (count > arr.length) { throw new Error('error arguments: count is greater than length of array') } let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index while (i-- > min) { index = Math.floor((i + 1) * Math.random()) temp = shuffled[index] shuffled[index] = shuffled[i] shuffled[i] = temp } return shuffled.slice(min) } /** * @author: clay * @data: 2019/08/15 * @description: graph utils */ import node from './node' import anchor from './anchor' import edge from './edge' import collapse from './collapse' /** * 比较两个对象的内容是否相同(两个对象的键值都相同) * @param obj1 * @param obj2 * @returns {*} */ const isObjectValueEqual = function(obj1, obj2) { let o1 = obj1 instanceof Object let o2 = obj2 instanceof Object // 不是对象的情况 if (!o1 || !o2) { return obj1 === obj2 } // 对象的属性(key值)个数不相等 if (Object.keys(obj1).length !== Object.keys(obj2).length) { return false } // 判断每个属性(如果属性值也是对象则需要递归) for (let attr in obj1) { let t1 = obj1[attr] instanceof Object let t2 = obj2[attr] instanceof Object if (t1 && t2) { return isObjectValueEqual(obj1[attr], obj2[attr]) } else if (obj1[attr] !== obj2[attr]) { return false } } return true } /** * 生成uuid算法,碰撞率低于1/2^^122 * @returns {string} */ const generateUUID = function() { let d = new Date().getTime() // x 是 0-9 或 a-f 范围内的一个32位十六进制数 let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { let r = (d + Math.random() * 16) % 16 | 0 d = Math.floor(d / 16) return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16) }) return uuid } export default { node, anchor, edge, collapse, // 通用工具类函数 isObjectValueEqual, generateUUID, deepClone, getRandomArrayElements }