三十秒完成 code
距离
两点之间距离
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3);
任意维度两个点的距离(欧几里得距离)
const euclideanDistance = (a, b) =>
Math.hypot(...Object.keys(a).map((k) => b[k] - a[k]));
euclideanDistance([1, 1], [2, 3]);
euclideanDistance([1, 1, 1], [2, 3, 2]);
产生随机数
- min <= num <= max
function Random(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}
设备厘米转像素
function getDPI() {
var arrDPI = new Array();
if (window.screen.deviceXDPI != undefined) {
arrDPI[0] = window.screen.deviceXDPI;
arrDPI[1] = window.screen.deviceYDPI;
} else {
var tmpNode = document.createElement("DIV");
tmpNode.style.cssText =
"width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
document.body.appendChild(tmpNode);
arrDPI[0] = parseInt(tmpNode.offsetWidth);
arrDPI[1] = parseInt(tmpNode.offsetHeight);
tmpNode.parentNode.removeChild(tmpNode);
}
return arrDPI;
}
function cmToPx(cm, dpi = getDPI()) {
return Math.round((cm * dpi[0] ? dpi[0] : dpi) / 2.54);
}
数据的操作
从树状中获取路径(查找到所有上级节点到自己的路径)
function findParentId(tree, { value: id, key = "id" }) {
if (tree[key] === id) {
return [id];
}
if (tree.children) {
for (let i = 0; i < tree.children.length; i++) {
const result = findParentId(tree.children[i], { value: id, key });
if (result.length > 0) {
result.unshift(tree[key]);
return result;
}
}
}
return [];
}
在树状的数据结构中,查找符合条件的节点(树)
返回符合条件的节点(不包含上下级)
function findNode(tree, { value: id, key = "id" }) {
if (tree[key] === id) {
return tree;
}
if (tree.children) {
for (let i = 0; i < tree.children.length; i++) {
const result = findNode(tree.children[i], { value: id, key });
if (result) {
return result;
}
}
}
return null;
}
返回符合条件的节点以及其父节点的完整的树(重在过滤)
function filterTree(tree, condition) {
return tree.filter((item) => {
if (condition(item)) {
return true;
} else if (item.children && item.children.length) {
item.children = this.filterDepartmentTree(item.children, val);
return item.children.length;
}
return false;
});
}
扁平化
数组扁平化
const flatten = (arr) => arr.reduce((a, v) => a.concat(v), []);
flatten([1, [2], 3, 4]);
对象扁平化
const flattenObject = (obj) =>
Object.keys(obj).reduce((acc, k) => {
if (typeof obj[k] === "object") Object.assign(acc, flattenObject(obj[k]));
else acc[k] = obj[k];
return acc;
}, {});
flattenObject({ a: { b: { c: 1 } }, d: 1 });
平铺数组变树状结构
function arrayToTree(arr, id = "id", pid = "pid", children = "children") {
let data = JSON.parse(JSON.stringify(arr));
let result = [];
let hash = {};
data.forEach((item, index) => {
hash[data[index][id]] = data[index];
});
data.forEach((item) => {
let hashVP = hash[item[pid]];
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(item);
} else {
result.push(item);
}
});
return result;
}