一些有用的javascript函数
作者:不爱喝橙子汁
/**
* 类型检测函数
* 为typeof关键字的增强版,可以准确判断null,date类型
* 原理是使用V8引擎最初的toString方法观察数据类型
* @author 不爱喝橙子汁
* @version 1.0.0
* @param {Object} obj 任意对象,例如null,undefined,date
* @return {String} 类型的全小写字符串
*/
function type(obj) {
return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();
}
/**
* 节流
* 在给定时间内只有第一次的操作会返回结果
* 结合了防抖的思路:在delay时间内生成定时器,一旦到了delay的时间就返回结果
* 当用户只点击了一次的时候,在delay时间后得到结果
* 当用户点击了多次的时候,在delay时间后得到第一次的结果,其余的被节流阀忽视掉
* @author 不爱喝橙子汁
* @version 1.0.0
* @param {Function} fn 要包装的回调函数
* @param {number} delay 延迟时间,单位ms,默认500
* @return {Function} 被节流函数劫持的新的函数
*/
function throttle(fn, delay = 500) {
let last = 0;
let timer = null;
return function () {
let args = arguments;
let now = +new Date();
let context = this;
if (now - last < delay) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(context, args);
}, delay);
} else {
last = now;
fn.apply(context, args);
}
}
}
/**
* 防抖
* 在delay时间后得到结果
* 如果没等到delay的时间一直触发则永远也得不到结果
* @author 不爱喝橙子汁
* @version 1.0.0
* @param {Function} fn 要包装的回调函数
* @param {number} delay 延迟时间,单位ms,默认500
* @return {Function} 被防抖函数劫持的新的函数
*/
function debounce(fn, delay = 500) {
let timer = null;
return function () {
let args = arguments;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
/**
* 获取地图上两点间距离。单位:米
* @param {lat1} 第一个点的纬度
* @param {lon1} 第一个点的经度
* @param {lat2} 第二个点的纬度
* @param {lon2} 第二个点的经度
* @author 不爱喝橙子汁
*/
export function getDistance(lat1, lon1, lat2, lon2) {
const radLat1 = (lat1 * Math.PI) / 180.0;
const radLat2 = (lat2 * Math.PI) / 180.0;
const a = radLat1 - radLat2;
const b = (lon1 * Math.PI) / 180.0 - (lon2 * Math.PI) / 180.0;
let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378137;
s = Math.round(s * 10000) / 10000;
return s;
}
// 把若干数组按指定的字段名进行分组
function groupBy(list, propName) {
return list.reduce((acc, item) => {
const key = item[propName];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {});
}
// 深拷贝对象
function deepClone(obj) {
if (obj === null) return null;
if (typeof obj !== 'object') return obj;
if (obj instanceof Date) {
let date = new Date();
date.setTime(obj.getTime());
return date;
}
if (obj instanceof RegExp) {
let re = new RegExp(obj.source);
re.lastIndex = obj.lastIndex;
return re;
}
let newObj = new obj.constructor();
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = deepClone(obj[key]);
}
}
return newObj;
}
/**
* 提取若干数组中指定字段组合成一个新数组
*/
function extractProps(arr, prop) {
return arr.map((item) => item[prop]);
}
/**
* 提取对象中的指定的属性,返回一个新对象
*/
function pickProps(obj, props) {
if (typeof obj !== 'object') {
return obj;
}
const newObj = {};
props.forEach((prop) => {
newObj[prop] = obj[prop];
});
return newObj;
}
浙公网安备 33010602011771号