🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

js-util-libs

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-util-libs - npm Package Compare versions

Comparing version
1.2.1
to
1.2.2
+21
src/array/arrayToTree/__tests__/index.spec.js
describe("扁平数据转tree", () => {
it("arrayToTree", () => {
const { arrayToTree } = require("../index");
let arr = [
{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
]
const target = [{
"id": 1,
"name": "部门1",
"pid": 0,
"children": [{
"id": 2,
"name": "部门2",
"pid": 1,
"children": []
}]
}]
expect(arrayToTree(arr)).toEqual(target);
});
});
// 扁平数据结构转Tree
exports.arrayToTree = (items) => {
const result = []; // 存放结果集
const itemMap = {}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
};
}
itemMap[id] = {
...item,
children: itemMap[id]["children"],
};
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
};
}
itemMap[pid].children.push(treeItem);
}
}
return result;
};
describe("数组扁平化", () => {
it("测试flat方法", () => {
const { flat } = require("../index");
const arr = [
4,
[1,2],
88,
[
[2,8],
8
]
]
expect(flat(arr)).toEqual([4,1,2,88,2,8,8]);
});
});
//数组扁平化
const flat = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flat(cur) : cur);
}, []);
};
exports.flat = flat;
// 数组乱序
exports.arrScrambling = (arr) => {
for (let i = 0; i < arr.length; i++) {
const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
}
return arr;
}
// 数组去重
export { unique } from "./unique/index.js"
// 数组扁平化(降维)
export { flat } from "./flat/index.js"
// 数组扁平化(降维)
export { arrayToTree } from "./arrayToTree/index.js"
describe("数组去重", () => {
it("测试unique方法", () => {
const { unique } = require("../index");
const arr = [1,1,2,44,66,22,44,66]
expect(unique(arr)).toEqual([1,2,44,66,22]);
});
});
//数组去重
function unique(arr) {
let appeard=new Set()
return arr.filter(item=>{
//创建一个可以唯一标识对象的字符串id
let id = item+JSON.stringify(item)
if (appeard.has(id)) {
return false
} else {
appeard.add(id)
return true
}
})
}
exports.unique = unique;
// 加载样式文件
exports.loadStyle = (url) => {
try {
document.createStyleSheet(url);
} catch (e) {
var cssLink = document.createElement("link");
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
cssLink.href = url;
var head = document.getElementsByTagName("head")[0];
head.appendChild(cssLink);
}
}
// 获取随机字符串 len为字符串长度
exports.randomString = (len) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
let strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
// 生成指定范围随机数
exports.randomRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// 数组中获取随机数
exports.randomNum = arr => arr[Math.floor(Math.random() * arr.length)];
+48
-43

@@ -11,3 +11,3 @@ // 防抖节流

export { shallCopy }
from "./shallCopy/index.js";
from "./src/shallCopy/index.js";

@@ -19,58 +19,50 @@ // call apply bind

// 时间戳转时间格式 YYYY-mm-dd HH:MM:SS
export { dateFormat }
from "./dateFormat/index.js";
export { dateFormat, beforeDateFormat, getWeek }
from "./src/dateFormat/index.js";
// 转义字符转为前端展示字符号
export { escapeHtml }
from "./escapeHtml/index.js";
from "./src/escapeHtml/index.js";
// 匹配字符串中所有的图片src
export { matchingAllImg }
from "./matchingAllImg/index.js";
from "./src/matchingAllImg/index.js";
// 原生实现鼠标滚动动画缓冲
export { scrollAnimation }
from "./scrollAnimation/index.js";
export { scrollAnimation, scrollToTop }
from "./src/scrollAnimation/index.js";
// 异步加载多个外部js方案
export { loadScript }
from "./loadScript/index.js";
from "./src/loadScript/index.js";
// 获取url参数
export { getUrlParms }
from "./getUrlParms/index.js";
from "./src/getUrlParms/index.js";
// 冒泡排序法
export { bubbleSort }
from "./sort/bubble_sort/index.js";
from "./src/sort/bubble_sort/index.js";
// 计数排序法
export { counterSort }
from "./sort/counter_sort/index.js";
from "./src/sort/counter_sort/index.js";
// 插入排序法
export { insertSort }
from "./sort/insert_sort/index.js";
from "./src/sort/insert_sort/index.js";
// 归并排序
export { mergeSort }
from "./sort/counter_sort/index.js";
from "./src/sort/counter_sort/index.js";
// 快速排序
export { sort }
from "./sort/quick_sort/index.js";
from "./src/sort/quick_sort/index.js";
// 选择排序
export { selectionSort }
from "./sort/selection_sort/index.js";
from "./src/sort/selection_sort/index.js";
// 数组扁平化
export { flat }
from "./flat/index.js";
// 数组去重
export { unique }
from "./unique/index.js";
// 邮箱 手机号 URL 微信号 qq号 车牌号 密码强度校验 是否含中文 邮编号 16进制颜色 身份证号 ipv4 数字 对象 空对象 数组 基本数据类型
// 邮箱 手机号 URL 微信号 qq号 车牌号 密码强度校验 是否含中文 邮编号 16进制颜色 身份证号 ipv4 数字 对象 空对象 数组 基本数据类型 银行卡号码校验(luhn算法)
export {

@@ -87,2 +79,3 @@ isEmail,

isRGB,
bankCardCheck,
isIdCard,

@@ -94,48 +87,60 @@ isIpv4,

isArray,
isType
isType,
}
from "./check/index.js";
from "./src/check/index.js";
// 判断手机是Andoird还是IOS
export { getOSType }
from "./getOSType/index.js";
from "./src/getOSType/index.js";
// 判断手机是Andoird还是IOS
export { cliboard }
from "./cliboard/index.js";
from "./src/cliboard/index.js";
// 判断是浏览器内核
export { checkBrowser }
from "./checkBrowser/index.js";
from "./src/checkBrowser/index.js";
// cookie 设置 获取 移除
export { cookieSet, cookieGet, cookieRemove }
from "./cookie/index.js";
from "./src/cookie/index.js";
// 获取 html 文本中转化为 html 后的纯文本信息
export { getHtmlText }
from "./getHtmlText/index.js";
from "./src/getHtmlText/index.js";
//实现base64解码加密
export { base64Decode ,base64Encode }
from "./base64/index.js";
export { base64Decode, base64Encode }
from "./src/base64/index.js";
//实现utf-8解码加密
export { utf8Decode ,utf8Encode }
from "./base64/index.js";
export { utf8Decode, utf8Encode }
from "./src/base64/index.js";
//去除空格
export { trim }
from "./trim/index.js";
export { trim }
from "./trim/index.js";
// 数字千分位分割
export { thousandth }
from "./thousandth/index.js";
export { thousandth }
from "./src/thousandth/index.js";
// 将数字转换为大写金额
export { changeToChinese }
from "./changeToChinese/index.js";
export { changeToChinese }
from "./src/changeToChinese/index.js";
// 文件大小格式化
export { formatSize }
from "./formatSize/index.js";
export { formatSize }
from "./src/formatSize/index.js";
// 加载样式文件
export { loadStyle }
from "./src/loadStyle/index.js";
// 扁平数据结构转Tree 数组乱序 去重 扁平化
export { arrayToTree , arrScrambling, unique, flat}
from "./src/array/index.js";
// 1、指定范围随机数 2、随机长度字符串 3、数组随机数
export { randomString, randomRange, randomNum } from "./src/random/index.js"
{
"name": "js-util-libs",
"description": "js常见的函数工具库",
"version": "1.2.1",
"version": "1.2.2",
"author": "fuzhaoyang <932647051@qq.com>",

@@ -27,5 +27,8 @@ "license": "MIT",

"dateFormat",
"beforeDateFormat",
"getWeek",
"escapeHtml",
"matchingAllImg",
"scrollAnimation",
"scrollToTop",
"loadScript",

@@ -42,2 +45,3 @@ "getUrlParms",

"unique",
"arrScrambling",
"isEmail",

@@ -55,2 +59,3 @@ "isPhone",

"isIpv4",
"bankCardCheck",
"getOSType",

@@ -75,5 +80,10 @@ "cliboard",

"changeToChinese",
"formatSize"
"formatSize",
"loadStyle",
"arrayToTree",
"randomString",
"randomRange",
"randomNum"
],
"homepage": "https://github.com/fuzhaoyang/js-util-libs.git"
}
+87
-60

@@ -13,68 +13,92 @@ # js-util-libs(函数库)

1、防抖节流
1、防抖节流
2、深拷贝
2、深拷贝
3、浅拷贝
3、浅拷贝
4、call,apply,bind
4、call,apply,bind
5、时间戳转时间格式
6、转义字符转换
6、转义字符转换
7、匹配字符串中所有图片src
7、匹配字符串中所有图片src
8、复制文本到粘贴板
8、滚动条滚动动画缓冲
9、判断是浏览器内核
9、异步加载外部多个js(动态插入)
10、获取HTML中的纯文本信息
10、获取地址栏url参数
11、去除空格
11、6种排序方式
12、数字千分位分割(10,000,000)
1:冒泡排序
13、将阿拉伯数字翻译成中文的大写数字(五仟二百二十二)
2:计数排序
14、文件大小格式化 (B,KB,MB,GB)
3:插入排序
15、动态加载外部样式文件
4:归并排序
16、异步加载外部多个js(动态插入)
5:快速排序
17、获取地址栏url参数
6:选择排序
18、滚动条滚动
12、数组扁平化
1.动画缓冲(scrollAnimation)
13、数组去重
2.滚动页面到顶部(scrollToTop)
14、复制文本到粘贴板
19、时间戳转格式
15、判断是浏览器内核
1:YYYY-MM-DD HH:MM:SS
16、获取HTML中的纯文本信息
2:刚刚、几天前、几个月前、几年前
17、去除空格
3:星期几
18、数字千分位分割(10,000,000)
20、随机数
19、将阿拉伯数字翻译成中文的大写数字(五仟二百二十二)
1:指定长度随机字符串
20、文件大小格式化 (B,KB,MB,GB)
2:范围内随机数
21、Base64
3:数组取随机数
1.加密
21、6种排序方式
2.解密
1:冒泡排序
22、UTF-8
2:计数排序
1.加密
3:插入排序
2.解密
4:归并排序
23、cookie
5:快速排序
6:选择排序
22、数组
1.扁平数据结构转Tree
2.去重
3.扁平化(降维)
23、Base64
1.加密
2.解密
24、UTF-8
1.加密
2.解密
25、cookie
1.设置

@@ -84,56 +108,59 @@

3.移除
3.移除
26、常用校验
24、常用校验
1.邮箱校验
1.邮箱校验
2.手机号校验
2.手机号校验
3.微信号校验
3.微信号校验
4.QQ号校验
4.QQ号校验
5.车牌号校验
5.车牌号校验
6.密码强度校验
6.密码强度校验
7.是否包含中文校验
7.是否包含中文校验
8.邮编号校验
8.邮编号校验
9.16进制颜色校验
9.16进制颜色校验
10.身份证号校验
10.身份证号校验
11.Ipv4校验
11.Ipv4校验
12.手机是Andoird还是IOS
12.手机是Andoird还是IOS
13.是否数字
13.是否数字
14.是否对象
14.是否对象
15.是否空对象
15.是否空对象
16.是否数组
16.是否数组
17.数据类型判断
18、银行卡号码校验(luhn算法)
## 欢迎大家提PR扩充函数库,为开源社区贡献自己一份力
提Pr步骤
1、src底下创建自己模块函数的文件夹
2、函数模块包含markdow说明,有自己测试用例(必须)
3、根部index.js导出函数
4、packjson keywords里写自己函数关键字
## 欢迎大家提 PR 扩充函数库,为开源社区贡献自己一份力
提 Pr 步骤
1、src 底下创建自己模块函数的文件夹
2、函数模块包含 markdow 说明,有自己测试用例(必须)
3、根部 index.js 导出函数
4、packjson keywords 里写自己函数关键字
5、npm test 跑测试用例
6、不要修改packjson版本号,版本号为线上最新用户使用版本
7、Pull requests 测试用例过后,静等作者合代码
6、不要修改 packjson 版本号,版本号为线上最新用户使用版本
7、Pull requests 测试用例过后,静等作者合代码
## Contact me(联系我)
![image](https://user-images.githubusercontent.com/25168173/154791040-09b5e289-5533-4aa2-9e6d-cb11eabfddf3.png)
## 我的博客
https://fuchaoyang.com

@@ -140,0 +167,0 @@ ![image](https://user-images.githubusercontent.com/25168173/154791015-750d04e4-02d4-4ebb-a559-5e3331003309.png)

@@ -17,3 +17,4 @@ describe("常用校验方法", () => {

checkNum,
isEmptyObject
isEmptyObject,
bankCardCheck
} = require("../index");

@@ -72,7 +73,11 @@ // 邮箱测试

//判断是否为{}空对象
expect(isEmptyObject({})).toBe(true);
expect(isEmptyObject("66")).toBe(false);
expect(isEmptyObject({a:4})).toBe(false);
//判断是否为{}空对象
expect(isEmptyObject({})).toBe(true);
expect(isEmptyObject("66")).toBe(false);
expect(isEmptyObject({ a: 4 })).toBe(false);
// 银行卡号码校验(luhn算法)
expect(bankCardCheck(4485275742308327)).toBe(true);
expect(bankCardCheck(6011329933655299)).toBe(false);
});
});

@@ -83,18 +83,33 @@ // 是否邮箱

*/
exports.checkNum = value => {
return typeof value === 'number' && !isNaN(value);
}
exports.checkNum = (value) => {
return typeof value === "number" && !isNaN(value);
};
//判断是否为对象
const isObject = val =>
typeof val === "function" || (typeof val === "object" && !!val);
exports.isObject = isObject;
//判断是否为对象
const isObject = (val) =>
typeof val === "function" || (typeof val === "object" && !!val);
exports.isObject = isObject;
//判断是否为{}空对象
exports.isEmptyObject = val => isObject(val) && JSON.stringify(val) == "{}";
//判断是否为{}空对象
exports.isEmptyObject = (val) => isObject(val) && JSON.stringify(val) == "{}";
//判断是否为数组
exports.isArray = val => Array.isArray(val);
//判断是否为数组
exports.isArray = (val) => Array.isArray(val);
// 判断当前数据类型
exports.isType = value => Object.prototype.toString.call(value).slice(8,-1);
exports.isType = (value) => Object.prototype.toString.call(value).slice(8, -1);
// 银行卡号码校验(luhn算法)
exports.bankCardCheck = (num) => {
let arr = (num + "")
.split("")
.reverse()
.map((x) => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce(
(acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9),
0
);
sum += lastDigit;
return sum % 10 === 0;
};

@@ -5,10 +5,28 @@ /**

exports.checkBrowser = () => {
const u = navigator.userAgent;
const obj = {
trident: u.indexOf("Trident") > -1, //IE内核
presto: u.indexOf("Presto") > -1, //opera内核
webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
};
return Object.keys(obj)[Object.values(obj).indexOf(true)];
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie") ? { //ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1])
} : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
type: "IE",
version: 11
} : 0 <= t.indexOf("edge") ? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1])
} : 0 <= t.indexOf("firefox") ? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1])
} : 0 <= t.indexOf("chrome") ? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1])
} : 0 <= t.indexOf("opera") ? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1])
} : 0 <= t.indexOf("Safari") ? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1])
} : {
type: t,
version: -1
}
};
describe("时间格式化函数", () => {
it("测试时间格式化方法", () => {
const { dateFormat } = require("../index");
const { dateFormat, beforeDateFormat, getWeek } = require("../index");
const timeStamp = 1645414395327;

@@ -8,3 +8,5 @@ expect(dateFormat("YYYY-mm-dd HH:MM:SS", timeStamp)).toEqual('2022-02-21 11:33:15');

expect(dateFormat("YYYY-mm-dd", timeStamp)).toEqual('2022-02-21');
console.log(beforeDateFormat(1645414395327))
console.log(getWeek(1645414395327))
});
});

@@ -6,21 +6,76 @@ // 格式化日期 dateFormat("YYYY-mm-dd HH:MM:SS", date)

const opt = {
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString(), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString(), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
let k;
for (k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
);
}
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
);
}
}
return fmt;
};
};
// 刚刚、几天前、几个月前、几年前
exports.beforeDateFormat = function(current) {
if (!current) {
return;
}
//将字符串转换成时间格式
let timePublish = new Date(current);
let timeNow = new Date();
let minute = 1000 * 60;
let hour = minute * 60;
let day = hour * 24;
let month = day * 30;
let year = month * 12;
let diffValue = timeNow - timePublish;
let diffMonth = diffValue / month;
let diffWeek = diffValue / (7 * day);
let diffDay = diffValue / day;
let diffHour = diffValue / hour;
let diffMinute = diffValue / minute;
let diffYear = diffValue / year;
if (diffValue < 0) {
result = "刚刚";
} else if (diffYear > 1) {
result = parseInt(diffYear) + "年前";
} else if (diffMonth > 1) {
result = parseInt(diffMonth) + "月前";
} else if (diffWeek > 1) {
result = parseInt(diffWeek) + "周前";
} else if (diffDay > 1) {
result = parseInt(diffDay) + "天前";
} else if (diffHour > 1) {
result = parseInt(diffHour) + "小时前";
} else if (diffMinute > 1) {
result = parseInt(diffMinute) + "分钟前";
} else {
result = "刚刚发表";
}
return result;
};
// 星期几
exports.getWeek = (current) => {
const week = (current ? new Date(current) : new Date()).getDay();
const map = {
0: '星期日',
1: '星期一',
2: '星期二',
3: '星期三',
4: '星期四',
5: '星期五',
6: '星期六'
}
return map[week];
}
// 匹配字符串中所有图片src
exports.scrollAnimation = (currentY, targetY) => {
// 获取当前位置方法
// const currentY = document.documentElement.scrollTop || document.body.scrollTop
// 获取当前位置方法
// const currentY = document.documentElement.scrollTop || document.body.scrollTop
// 计算需要移动的距离
const needScrollTop = targetY - currentY;
let _currentY = currentY;
setTimeout(() => {
// 一次调用滑动帧数,每次调用会不一样
const dist = Math.ceil(needScrollTop / 10);
_currentY += dist;
window.scrollTo(_currentY, currentY);
// 如果移动幅度小于十个像素,直接移动,否则递归调用,实现动画效果
if (needScrollTop > 10 || needScrollTop < -10) {
scrollAnimation(_currentY, targetY);
} else {
window.scrollTo(_currentY, targetY);
// 计算需要移动的距离
const needScrollTop = targetY - currentY;
let _currentY = currentY;
setTimeout(() => {
// 一次调用滑动帧数,每次调用会不一样
const dist = Math.ceil(needScrollTop / 10);
_currentY += dist;
window.scrollTo(_currentY, currentY);
// 如果移动幅度小于十个像素,直接移动,否则递归调用,实现动画效果
if (needScrollTop > 10 || needScrollTop < -10) {
scrollAnimation(_currentY, targetY);
} else {
window.scrollTo(_currentY, targetY);
}
}, 1);
};
// 滑滚动页面到顶部
exports.scrollToTop = () => {
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, scrollTop - scrollTop / 8);
}
}, 1);
};
};
describe("数组扁平化", () => {
it("测试flat方法", () => {
const { flat } = require("../index");
const arr = [
4,
[1,2],
88,
[
[2,8],
8
]
]
expect(flat(arr)).toEqual([4,1,2,88,2,8,8]);
});
});
//数组扁平化
const flat = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flat(cur) : cur);
}, []);
};
exports.flat = flat;
describe("数组去重", () => {
it("测试unique方法", () => {
const { unique } = require("../index");
const arr = [1,1,2,44,66,22,44,66]
expect(unique(arr)).toEqual([1,2,44,66,22]);
});
});
//数组去重
function unique(arr) {
let appeard=new Set()
return arr.filter(item=>{
//创建一个可以唯一标识对象的字符串id
let id = item+JSON.stringify(item)
if (appeard.has(id)) {
return false
} else {
appeard.add(id)
return true
}
})
}
exports.unique = unique;