提交 8c636bfc authored 作者: supj's avatar supj

1、将外部库迁移初始化。已不维护

上级
.DS_Store
node_modules
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
/package-lock.json
/dist/compatible-tools.js
/dist/
/yarn.lock
build
example
docs
babel.config.js
.prettierignore
prettier.config.js
postcss.config.js
.eslintrc.js
.travis.yml
.eslintrc.js
.eslintignore
yarn.lock
jest.config.js
cypress.json
node_modules
.browserslistrc
yarn-error.log
npm-debug.log
dist
test
src
lib/*/*.map
{
"presets": [
["@babel/env"]
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
import {terser} from 'rollup-plugin-terser';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import path from "path";
const pkg = require('../package.json')
const resolveFile = (...args) => path.resolve(...args);
let inputFile=resolveFile("./src/index.js")
export default {
input: inputFile,
output: [
{
file:resolveFile(pkg.main),
format: 'cjs',
exports: "named"
},
// 输出 es 规范的代码
{
file: resolveFile(pkg.module),
format: 'esm',
sourcemap: false,
exports: "named"
}
],
plugins: [
resolve(), commonjs(),
babel({runtimeHelpers: true, exclude: 'node_modules/**',}),
terser(),
]
};
差异被折叠。
差异被折叠。
{
"name": "mf-js-lib",
"miniprogram": "lib/cjs",
"version": "0.0.1",
"private": false,
"license": "MIT",
"keywords": [],
"description": "当前JS版本已废弃,有问题请使用TS改写的版本",
"scripts": {
"build": "babel src -d lib",
"lib": " rimraf ./lib && rollup -c ./build/rollup.config.js"
},
"main": "./lib/cjs/index.cjs",
"module": "./lib/esm/index.mjs",
"exports": {
"node": {
"import": "./lib/esm/index.mjs",
"require":"./lib/cjs/index.cjs"
},
"default": "./lib/esm/index.mjs"
},
"types": "./index.d.ts",
"files": [
"lib",
"test",
"index.d.ts",
"typings.json"
],
"repository": {
"type": "git",
"url": "x"
},
"homepage": "x",
"dependencies": {
},
"peerDependencies": {},
"devDependencies": {
"@babel/cli": "^7.15.7",
"@babel/core": "^7.15.5",
"@babel/plugin-transform-arrow-functions": "^7.14.5",
"@babel/plugin-transform-block-scoping": "^7.15.3",
"@babel/plugin-transform-classes": "^7.15.4",
"@babel/plugin-transform-runtime": "^7.15.0",
"@babel/polyfill": "^7.12.1",
"@babel/preset-env": "^7.4.5",
"@babel/types": "^7.15.6",
"@types/node": "^14.14.35",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-remove-console": "^6.9.4",
"rimraf": "^3.0.0",
"rollup": "^2.57.0",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "^5.1.1",
"core-js": "^2.6.5"
}
}
/**
* 将数据分组
* @param list 数据源
* @param groupNumber 分组的个数
* @returns {[]|*} 返回分组后的列表
*/
function groupingList(list, groupNumber) {
if (list && groupNumber > 0) {
const groupList = [];
let endLength = list.length;
let startIndex = 0;
let endIndex = groupNumber;
while (startIndex < endLength) {
groupList.push(list.slice(startIndex, endIndex))
startIndex = startIndex + groupNumber
endIndex = endIndex + groupNumber
}
return groupList;
}
return list;
}
/**
* 补齐数据
* 返回新的数据
* @param list
* @param groupNum
* @returns {*}
*/
function makeUpGroupList(list, groupNum) {
if (list && list.length > 0) {
const newList = [...list]
if (groupNum < 2) {
return newList;
}
let endCount = newList.length % groupNum;
if (endCount > 0) {//补全数据
for (let i = 0, len = groupNum - endCount; i < len; i++) {
newList.push({})
}
}
return newList;
}
return list;
}
module.exports = {
groupingList: groupingList,
makeUpGroupList: makeUpGroupList,
};
class CalendarHelper {
/**
* 获取当前时间 (2018-08-15)
*/
static getCurrentFormatDateString() {
const date = new Date();
return date.getFullYear() + "-" + CalenderUtils.getFullNumber(date.getMonth() + 1) + "-" + CalenderUtils.getFullNumber(date.getDate());
}
/**
* 获取日历数据
* @param year
* @param month
*/
static getCalendarData(year, month) {
let newDatas = [];
const monthInfo = new MonthInfo(year, month);
const weekDay = CalenderUtils.getWeekDay(year, month);
if (weekDay > 0) {
//月份的第一天不是表的第一天。需要在前面插入上个月数据
const lastMonthInfo = CalenderUtils.getLastMonthInfo(year, month);
const lastMonthDays = CalenderUtils.getMonthDays(lastMonthInfo.year, lastMonthInfo.month)
for (let j = 0; j < weekDay; j++) {
const currentDay = lastMonthDays - weekDay + 1 + j;
const dayInfo = new DayInfo(lastMonthInfo.year, lastMonthInfo.month, currentDay);
dayInfo.setSupplementDay(true);
newDatas.push(dayInfo);
}
}
newDatas = newDatas.concat(monthInfo.dayItems);
const size = newDatas.length;
//为了列表显示(个数必须是7的倍数),必须补充空数据
const emptyDays = 7 - size % 7;
if (emptyDays < 7) {
const nextMonthInfo = CalenderUtils.getNextMonthInfo(year, month)
for (let j = 0; j < emptyDays; j++) {
let dayInfo = new DayInfo(nextMonthInfo.year, nextMonthInfo.month,(j+1));
dayInfo.setSupplementDay(true);
newDatas.push(dayInfo)
}
}
monthInfo.dayItems = newDatas;
return monthInfo;
}
/**
* 获取上个月的数据
* @param year
* @param month
*/
static getLastMonthData(year, month) {
const info = CalenderUtils.getLastMonthInfo(year, month);
return CalendarHelper.getCalendarData(info.year, info.month)
}
/**
* 获取下个月的数据
* @param year
* @param month
*/
static getNextMonthData(year, month) {
const info = CalenderUtils.getNextMonthInfo(year, month);
return CalendarHelper.getCalendarData(info.year, info.month)
}
/**
* 获取当前月份的日历数据
*/
static getCurrentMonthData() {
const date = new Date();
return CalendarHelper.getCalendarData(date.getFullYear(), date.getMonth() + 1)
}
/**
* 获取日历基础数据(从当前月,往后推)
* @param count
* @returns {Array}
*/
static getCalendarDataList (count) {
const months = [];
let data = CalendarHelper.getCurrentMonthData();
months.push(data)
for (let i = 1; i < count; i++) {
data = CalendarHelper.getNextMonthData(data.year, data.month);
months.push(data)
}
return months;
}
}
class MonthInfo {
constructor(year, month) {
this.titleName = month;
this.year = year;
this.month = month;
this.dayItems = this.getDayItems();
}
getDayItems() {
const days = CalenderUtils.getMonthDays(this.year, this.month);
const dayItems = [];
for (let i = 1; i <= days; i++) {
const dayInfo = new DayInfo(this.year, this.month, i);
dayItems.push(dayInfo)
}
return dayItems;
}
toString() {
return "year= " + this.year + " month= " + this.month;
}
}
class DayInfo {
constructor(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.isSupplementDay = false;
this.titleName = day;
this.formatDay = this.getFormatDayString();
const date = new Date(this.formatDay);
date.setHours(0,0,0,0)
this.time =date .getTime();
}
setSupplementDay(isSupplement) {
this.isSupplementDay = isSupplement;
}
getFormatDayString() {
const monthNumberString = CalenderUtils.getFullNumber(this.month);
const dayNumberString = CalenderUtils.getFullNumber(this.day);
return this.year + "-" + monthNumberString + "-" + dayNumberString;
}
equal(object) {
if (object && object instanceof DayInfo) {
return this.year === object.currentYear && this.month === object.currentMonth && this.day === object.currentDay
}
return false;
}
toString() {
return "currentYear= " + this.year + " currentMonth= " + this.month + " currentDay= " + this.day;
}
}
class CalenderUtils {
static getFullNumber(num) {
if (num >= 10) {
return num;
}
return "0" + num;
}
static isLeapYear(year) {
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
}
/**
* 获取指定月份天数
* @param year
* @param month
* @returns {number}
*/
static getMonthDays(year, month) {
if (month == 2) {
return CalenderUtils.isLeapYear(year) ? 29 : 28;
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
}
return 30;
}
static getNextMonthInfo(year, month) {
const newMonth = month == 12 ? 1 : month + 1;
const newYear = month == 12 ? year + 1 : year;
return {year: newYear, month: newMonth}
}
static getLastMonthInfo(year, month) {
//获取上个月实际月份
const newMonth = month == 1 ? 12 : month - 1;
//获取实际年份
const newYear = month == 1 ? year - 1 : year;
return {year: newYear, month: newMonth}
}
/**
* 获取某年某月第一天是星期几
* @param year
* @param month
*/
static getWeekDay(year, month) {
const date = new Date(year, month - 1, 1);
return date.getDay();
}
}
module.exports = CalendarHelper
const dateConstants = require('./DateConstants')
class CountDownTimer {
/**
*
* @param millisInFuture 时间毫秒数
* @param countDownInterval 时间毫秒数(单位间隔)
*/
constructor(millisInFuture, countDownInterval) {
this.millisInFuture = millisInFuture;
this.mInterval = countDownInterval;
this.onFinishListener =undefined;
this.onCountDownListener=undefined;
this.timer = undefined;
}
addCountDownListener(listener){
if(listener && typeof listener ==='function'){
this.onCountDownListener=listener;
}
}
addFinishListener(listener){
if(listener && typeof listener ==='function'){
this.onFinishListener=listener;
}
}
start() {
if (!this.timer && this.onCountDownListener && typeof this.onCountDownListener==='function') {
let that = this;
this.timer = setInterval(() => {
that.millisInFuture = that.millisInFuture - that.mInterval;
if (that.millisInFuture > 0) {
that.onCountDownListener(CountDownTimer.getTimeInfo(that.millisInFuture));
} else {
that.cancel();
if(that.onFinishListener && typeof that.onFinishListener ==='function'){
that.onFinishListener();
}
}
}, that.mInterval);
}
}
cancel() {
if (this.timer) {
clearInterval(this.timer);
this.timer = undefined;
}
}
static getTimeInfo(time) {
let hourTime = time % dateConstants.dayMillis;//剩余的小时部分时间
let minuteTime = time % dateConstants.hourMillis;//剩余的分钟部分时间
let secondTime = time % dateConstants.minuteMillis;//剩余的秒部分时间
return {
time: time,
day:Math.floor(time/dateConstants.dayMillis),
hour: Math.floor(hourTime /dateConstants.hourMillis),
minute: Math.floor(minuteTime /dateConstants.minuteMillis),
second: Math.floor(secondTime /dateConstants.secondMillis),
format: (value) => {
return value >= 10 ? value : "0" + value;
}
}
}
}
module.exports = CountDownTimer;
const dayMillis = 86400000;//一天的毫秒数
const hourMillis = 3600000;//小时的毫秒数
const minuteMillis = 60000;//分的毫秒数
const secondMillis = 1000;//秒的毫秒数
module.exports = {
dayMillis:dayMillis,
hourMillis:hourMillis,
minuteMillis:minuteMillis,
secondMillis:secondMillis,
};
const dateConstants = require("./DateConstants")
function formatNumber(num) {
return num > 9 ? num : "0" + num;
}
function getDateInstance(date) {
if (date instanceof Date) {
return date;
}
if (typeof date === 'string' && date.indexOf('-') > 0) {//兼容ios new Date('2020-10-10') 返回Invalid Date
const reg = new RegExp("-", "g");
date = date.replace(reg, '/')
}
return new Date(date);
}
function isToday(date) {
let currentDate = new Date();
let orderDate = getDateInstance(date)
return currentDate.getFullYear() === orderDate.getFullYear() && orderDate.getMonth() === currentDate.getMonth() && orderDate.getDate() === currentDate.getDate();
}
//格式化日期 YYYY-MM-DD
function getFormatDate(date) {
const dateInstance = getDateInstance(date);
return dateInstance.getFullYear() + "-" + formatNumber(dateInstance.getMonth() + 1) + "-" + formatNumber(dateInstance.getDate());
}
//获取当前日期
function getCurrentFormatDate() {
return getFormatDate(new Date())
}
//获取当前日期所在月份的天数
function getDaysInMonth(date) {
const dateInstance = getDateInstance(date);
return getMonthDays(dateInstance.getFullYear(), dateInstance.getMonth() + 1);
}
function getWeekName(date, isEnglish = false) {
const dateInstance = getDateInstance(date);
const weekDay = dateInstance.getDay()
if (weekDay === 0) {
return isEnglish ? 'Sunday' : '周日';
} else if (weekDay === 1) {
return isEnglish ? 'Monday' : "周一";
} else if (weekDay === 2) {
return isEnglish ? 'Tuesday' : '周二';
} else if (weekDay === 3) {
return isEnglish ? 'Wednesday' : '周三';
} else if (weekDay === 4) {
return isEnglish ? 'Thursday' : '周四';
} else if (weekDay === 5) {
return isEnglish ? 'Friday' : '周五';
} else if (weekDay === 6) {
return isEnglish ? 'Saturday' : '周六';
}
return '';
}
function isLeapYear(year) {
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
}
/**
* 获取指定月份天数
* @param year
* @param month
* @returns {number}
*/
function getMonthDays(year, month) {
if (month === 2 || month === "2") {
return isLeapYear(year) ? 29 : 28;
}
const bigMonths = [1, 3, 5, 7, 8, 10, 12]
if (bigMonths.includes(month)) {
return 31;
}
return 30;
}
function getNextMonthInfo(year, month) {
const newMonth = month == 12 ? 1 : month + 1;
const newYear = month == 12 ? year + 1 : year;
return {year: newYear, month: newMonth}
}
function getLastMonthInfo(year, month) {
//获取上个月实际月份
const newMonth = month == 1 ? 12 : month - 1;
//获取实际年份
const newYear = month == 1 ? year - 1 : year;
return {year: newYear, month: newMonth}
}
function diffTime(startTime, endTime, unitTime) {
if (typeof startTime === 'number' && typeof endTime === 'number') {
const diffTimeNum = endTime - startTime
return Math.floor((diffTimeNum / unitTime) * 100) / 100
}
return undefined;
}
function diffYears(startTime, endTime) {
let number = diffMonths(startTime, endTime);
return Math.floor(number / 12 * 100) / 100;
}
function diffMonths(startTime, endTime) {
let miniTime = Math.min(startTime, endTime);
let maxTime = Math.max(startTime, endTime);
const startDate = getDateInstance(miniTime);
const endDate = getDateInstance(maxTime);
let diffYear = endDate.getFullYear() - startDate.getFullYear();
let startMonth = startDate.getMonth() + 1;
let endMonth = endDate.getMonth() + 1;
if (endMonth < startMonth) {
diffYear = diffYear - 1;
endMonth = endMonth + 12;
}
return Number.parseInt((diffYear * 12 + endMonth - startMonth).toFixed(0))
}
function diffDays(startTime, endTime) {
return diffTime(startTime, endTime, dateConstants.dayMillis)
}
function diffHours(startTime, endTime) {
return diffTime(startTime, endTime, dateConstants.hourMillis)
}
function diffMinutes(startTime, endTime) {
return diffTime(startTime, endTime, dateConstants.minuteMillis)
}
function diffSeconds(startTime, endTime) {
return diffTime(startTime, endTime, dateConstants.secondMillis)
}
///yyyy-MM-dd HH:mm:ss
const formatDateList = [
{
symbolList: ["yyyy", "YYYY"],
getValue: function (date) {
return formatNumber(date.getFullYear());
}
},
{
symbolList: ["MM"],
getValue: function (date) {
return formatNumber(date.getMonth() + 1);
}
},
{
symbolList: ["DD", "dd"],
getValue: function (date) {
return formatNumber(date.getDate());
}
},
{
symbolList: ["HH", "hh"],
getValue: function (date) {
return formatNumber(date.getHours());
}
},
{
symbolList: ["mm"],
getValue: function (date) {
return formatNumber(date.getMinutes());
}
},
{
symbolList: ["SS", "ss"],
getValue: function (date) {
return formatNumber(date.getSeconds());
}
},
]
function formatDateString(date, formatStyle) {
let format = String(formatStyle);
if (formatStyle) {
let dateInstance = getDateInstance(date);
formatDateList.forEach(formatItem => {
for (let i = 0, len = formatItem.symbolList.length; i < len; i++) {
if (format.indexOf(formatItem.symbolList[i]) >= 0) {
format = format.replace(formatItem.symbolList[i], formatItem.getValue(dateInstance))
break;
}
}
})
}
return format;
}
module.exports = {
getDateInstance: getDateInstance,
isToday: isToday,
formatNumber: formatNumber,
formatDateString: formatDateString,
getCurrentFormatDate: getCurrentFormatDate,
getDaysInMonth: getDaysInMonth,
getMonthDays: getMonthDays,
getWeekName: getWeekName,
isLeapYear: isLeapYear,
getLastMonthInfo: getLastMonthInfo,
getNextMonthInfo: getNextMonthInfo,
diffYears: diffYears,
diffMonths: diffMonths,
diffDays: diffDays,
diffHours: diffHours,
diffMinutes: diffMinutes,
diffSeconds: diffSeconds,
};
const eventsHolder = {
observerList: [],//观察对象列表
stickyEvents: [],//粘性事件(消息)
}
function getRegisterType(eventType) {
return eventType ? eventType : "defaultType"
}
class EventBus {
/**
* 发送粘性事件消息(同一个类型,只保留最后一个)
* @param msg 消息
* @param eventType 事件类型
*/
static postSticky(msg, eventType) {
const registerType = getRegisterType(eventType);
const findIndex = eventsHolder.stickyEvents.findIndex(item => item.eventType === registerType);
if (findIndex >= 0) {
eventsHolder.stickyEvents[findIndex].msg = msg;
} else {
eventsHolder.stickyEvents.push({
eventType: registerType,
msg: msg,
})
}
EventBus.post(msg, registerType);
}
/**
* 发送事件消息
* @param msg 消息
* @param eventType 事件类型
*/
static post(msg, eventType) {
const postType = getRegisterType(eventType);
eventsHolder.observerList.forEach(item => {
if (postType === item.eventType && item.subscriber && typeof item.subscriber === "function") {
item.subscriber({eventType: item.eventType, msg: msg});
}
})
}
/**
* //注册一个事件(同一类型只能注册一次,即同一函数名称名称,只能注册一次)
* @param observer 需要观察的对象
* @param eventType 观察的对象事件类型,可确省,默认为 "defaultType"
* @param sticky 是否是粘性事件,可确省,默认为false
* @param subscriber 订阅回调
*/
static register(observer, sticky = false, eventType = 'defaultType', subscriber) {
if (subscriber) {
const registerType = getRegisterType(eventType);
let findIndex = eventsHolder.observerList.findIndex(item => item.observer === observer && item.eventType === eventType);
if (findIndex < 0) {
if (sticky) {
let findEvent = eventsHolder.stickyEvents.find(item => item.eventType === registerType);
if (findEvent && subscriber && typeof subscriber === "function") {
subscriber(findEvent);
}
}
eventsHolder.observerList.push({
observer: observer,
subscriber: subscriber,
eventType: registerType,
})
}
}
}
/**
* 解除注册
* @param observer
*/
static unregister(observer) {
eventsHolder.observerList = eventsHolder.observerList.filter(item => item.observer !== observer);
}
/**
* 销毁所有(谨慎调用)
*/
static destroy() {
eventsHolder.stickyEvents = []
eventsHolder.observerList = []
}
}
module.exports = EventBus;
let vcity = {
11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南",
42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆",
51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃",
63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
};
function checkCard(code) {
//是否为空
// if(card === '')
// {
// return false;
//}
//校验长度,类型
if (isCardNo(code) === false) {
return false;
}
//检查省份
if (checkProvince(code) === false) {
return false;
}
//校验生日
if (checkBirthday(code) === false) {
return false;
}
//检验位的检测
if (checkParity(code) === false) {
return false;
}
return true;
}
//检查号码是否符合规范,包括长度,类型
function isCardNo(obj) {
//身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
let reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
if (reg.test(obj) === false) {
return false;
}
return true;
}
//取身份证前两位,校验省份
function checkProvince(obj) {
let province = obj.substr(0, 2);
if (vcity[province] == undefined) {
return false;
}
return true;
}
//检查生日是否正确
function checkBirthday(obj) {
let len = obj.length;
//身份证15位时,次序为省(3位)市(3位)年(2位)月(2位)日(2位)校验位(3位),皆为数字
if (len == '15') {
let re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
let arr_data = obj.match(re_fifteen);
let year = arr_data[2];
let month = arr_data[3];
let day = arr_data[4];
let birthday = new Date('19' + year + '/' + month + '/' + day);
return verifyBirthday('19' + year, month, day, birthday);
}
//身份证18位时,次序为省(3位)市(3位)年(4位)月(2位)日(2位)校验位(4位),校验位末尾可能为X
if (len == '18') {
let re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
let arr_data = obj.match(re_eighteen);
let year = arr_data[2];
let month = arr_data[3];
let day = arr_data[4];
let birthday = new Date(year + '/' + month + '/' + day);
return verifyBirthday(year, month, day, birthday);
}
return false;
}
//校验日期
function verifyBirthday(year, month, day, birthday) {
let now = new Date();
let now_year = now.getFullYear();
//年月日是否合理
if (birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day) {
//判断年份的范围(3岁到100岁之间)
let time = now_year - year;
if (time >= 0 && time <= 130) {
return true;
}
return false;
}
return false;
}
//校验位的检测
function checkParity(obj) {
//15位转18位
obj = changeFivteenToEighteen(obj);
let len = obj.length;
if (len == '18') {
let arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
let arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
let cardTemp = 0, i, valnum;
for (i = 0; i < 17; i++) {
cardTemp += obj.substr(i, 1) * arrInt[i];
}
valnum = arrCh[cardTemp % 11];
if (valnum == obj.substr(17, 1)) {
return true;
}
return false;
}
return false;
};
//15位转18位身份证号
function changeFivteenToEighteen(obj) {
if (obj.length == '15') {
let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let cardTemp = 0, i;
obj = obj.substr(0, 6) + '19' + obj.substr(6, obj.length - 6);
for (i = 0; i < 17; i++) {
cardTemp += obj.substr(i, 1) * arrInt[i];
}
obj += arrCh[cardTemp % 11];
return obj;
}
return obj;
}
module.exports={
checkCard:checkCard,
};
class LogUtils {
constructor(debug) {
this.enableDebug = debug
}
getTag(tag) {
return tag + '===================='
}
setEnableDebug(debug) {
this.enableDebug = debug
}
debug(msg) {
if (this.enableDebug) {
console.debug(msg)
}
}
debugWithTag(tag, msg) {
if (this.enableDebug) {
console.debug(this.getTag(tag), msg)
}
}
info(msg) {
if (this.enableDebug) {
console.info(msg)
}
}
infoWithTag(tag, msg) {
if (this.enableDebug) {
console.info(this.getTag(tag), msg)
}
}
log(msg) {
if (this.enableDebug) {
console.log(msg)
}
}
logWithTag(tag, msg) {
if (this.enableDebug) {
console.log(this.getTag(tag), msg)
}
}
error(msg) {
if (this.enableDebug) {
console.error(msg)
}
}
errorWithTag(tag, msg) {
if (this.enableDebug) {
console.error(this.getTag(tag), msg)
}
}
warn(msg) {
if (this.enableDebug) {
console.warn(msg)
}
}
warnWithTag(tag, msg) {
if (this.enableDebug) {
console.warn(this.getTag(tag), msg)
}
}
}
module.exports = LogUtils;
//克隆对象
function cloneObject(object) {
if (object instanceof Array) {
let newArray = [];
for (let i = 0, len = object.length; i < len; i++) {
newArray.push(cloneObject(object[i]));
}
return newArray;
} else if (object instanceof Object) {
let newObject = {};
for (let key in object) {
newObject[key] = cloneObject(object[key])
}
return newObject;
}
return object;
}
//将某个对象追加到当前对象中(扩展对象,类似java中的继承)
function extendObject(targetObject, sourceObject) {
if (!sourceObject || typeof (sourceObject) !== 'object') {//源对象为空或者不是对象时
return targetObject;
}
if (targetObject && typeof (sourceObject) === 'object') {
Object.keys(sourceObject).forEach(sourceKey=>{
if (typeof (targetObject[sourceKey]) === 'undefined') {//当前目标没有定义
targetObject[sourceKey] = sourceObject[sourceKey];
} else if (typeof (targetObject[sourceKey]) === 'object') {//当前目标不为空而且是对象时
extendObject(targetObject[sourceKey], sourceObject[sourceKey])
}
})
}
return targetObject;
}
//判断列表是是否包含特定的对象
function containObject(list, object) {
if (!list || list.length < 1) {
return false
}
for (let i = 0, len = list.length; i < len; i++) {
if(deepEqual(list[i],object)){
return true;
}
}
return false;
}
//深入比较对象(判断对象是否相等)
function deepEqual(object_1, object_2) {
let type1 = typeof object_1
let type2 = typeof object_2
if (type1 !== type2) {
return false
}
if (type1 === 'string' || type1 === 'number' || type1 === 'undefined' || type1 === 'boolean') {
return object_1 === object_2
}
if (type1 === 'object') {
if (type1 instanceof Array) {
if (object_1.length !== object_1.length) {
return false
}
if (!object_1.every(item => containObject(object_2, item))) {
return false
}
if (!object_2.every(item => containObject(object_1, item))) {
return false
}
return true
} else {
let keys_1 = Object.keys(object_1)
let keys_2 = Object.keys(object_2)
if (keys_1.length !== keys_2.length) {
return false
}
let filterKeys = keys_2.filter(key => keys_1.includes(key))
if (filterKeys.length !== keys_1.length) {
return false
}
for (let i = 0, len = keys_1.length; i < len; i++) {
let equal = deepEqual(object_1[keys_1[i]], object_2[keys_1[i]])
if (!equal) {
return false
}
}
return true
}
}
return false;
}
function getObjectByList(keysList, valuesObject) {
let newObject = {}
if (keysList && keysList.length > 0 && valuesObject && typeof valuesObject === 'object') {
for (let i = 0, len = keysList.length; i < len; i++) {
let key = keysList[i];
if (key) {
newObject[key] = valuesObject[key]
}
}
}
return newObject
}
function getObjectByObject(keysObject, targetObject) {
if (keysObject && targetObject && typeof keysObject === 'object' && typeof targetObject === 'object') {
let keys = Object.keys(keysObject)
return getObjectByList(keys,targetObject);
}
return {};
}
function getValueFromObject(obj,keyWords){
if(typeof obj ==='object' && keyWords && typeof keyWords==='string'){
if(obj[keyWords]){
return obj[keyWords];
}
let indexOf = keyWords.indexOf(".");
if(indexOf<0){
return obj[keyWords]
}else{
const keys=keyWords.split(".")
if(obj[keys[0]] && obj[keys[0]] instanceof Object){
const nextKeyWorks = keys.slice(1).join('.')
return getValueFromObject(obj[keys[0]] ,nextKeyWorks);
}
}
}
return "";
}
/**
* 监听属性 并执行监听函数
*/
function observe(obj, key,watchFun) {
if(obj && typeof obj==='object'){
let val = obj[key]; //给该属性设默认值
if(val){
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function(value) {
let oldVal = val;
val = value;
watchFun(value, oldVal);
},
get: function() {
return val;
}
})
}else{
let indexOf = key.indexOf(".");
if(indexOf>0){
const objKey=key.substring(0,indexOf)
let newKey=key.substr(indexOf+1);
observe(obj[objKey],newKey,watchFun)
}
}
}
}
/**
* 设置监听器
*/
function setWatcher(data, watch) {
Object.keys(watch).forEach(v => {
observe(data, v,watch[v]);
})
}
module.exports = {
getObjectByObject:getObjectByObject,
getObjectByList:getObjectByList,
getValueFromObject:getValueFromObject,
deepEqual:deepEqual,
containObject:containObject,
cloneObject:cloneObject,
extendObject:extendObject,
setWatcher:setWatcher,
};
const IdCardHelper = require("./IdCardHelper")
class StringHelper {
/**
* 替换所有
* @param content 当前文本
* @param pattern 旧字符串或者正则表达式
* @param newStr 要替换的内容
* @returns {*} 返回新的字符串
*/
static replaceAll(content, pattern, newStr) {
const reg = new RegExp(pattern, "g"); //创建正则RegExp对象
return content.replace(reg, newStr)
}
/**
* 判断是否是身份证
* @param codeStr
* @returns {boolean}
*/
static isIDCard(codeStr){
return IdCardHelper.checkCard(codeStr)
}
static isEmpty(str){
return !str || str.trim().length < 1;
}
/**
* 校验手机号(严格校验)
* //移动号段:134 135 136 137 138 139 147 148 150 151 152 157 158 159 165 172 178 182 183 184 187 188 195 198
* // 联通号段:130 131 132 145 146 155 156 166 167 171 175 176 185 186
* // 电信号段:133 149 153 173 174 177 180 181 189 191 199
* // 虚拟运营商:170
* 分组如下
* //130 131 132 133 134 135 136 137 138 139
* //145 146 147 148 149
* //150 151 152 153 155 156 157 158 159
* // 165 166 167
* //170 171 172 173 174 175 176 177 178
* //180 181 182 183 184 185 186 187 188 189
* // 191 195 198 199
* @param phone
* @returns {boolean}
*/
static isPhoneNumber(phone) {
const phoneStr=String(phone);
//手机号正则
if (/^1[38][0-9]{9}$/.test(phoneStr)) {//校验//130 131 132 133 134 135 136 137 138 139 180 181 182 183 184 185 186 187 188 189号段
return true;
}
if (/^14[56789][0-9]{8}$/.test(phoneStr)) {//校验14开头的号段
return true
}
if (/^15[012356789][0-9]{8}$/.test(phoneStr)) {//校验 1//150 151 152 153 155 156 157 158 159 开头的号段
return true;
}
if (/^16[567][0-9]{8}$/.test(phoneStr)) {//校验 // 165 166 167 开头的号段
return true;
}
if (/^17[012345678][0-9]{8}$/.test(phoneStr)) {//校验 //170 171 172 173 174 175 176 177 178 开头的号段
return true;
}
if (/^19[1589][0-9]{8}$/.test(phoneStr)) {//校验// 191 195 198 199 开头的号段
return true;
}
return false;
}
/**
* 判断是否是邮件地址
* @param email
* @returns {boolean}
*/
static isEmail(email) {
if (email) {
const regex = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
return regex.test(email)
}
return false
}
/**
* 从富文本中,查找img 标签,收集图片地址(只支持.png .jpg .jpeg 结尾)
* @param text 富文本
* @returns {[]} 返回图片列表
*/
static getImageListFromRichText(text){
const list = [];
let regular = /<img[^>]*>/g
let keysWords = text.match(regular)
if(keysWords && keysWords.length>0){
let srcReg = /http\S*((.jpg)|(.jpeg)|(.png))/g
keysWords.forEach(words=>{
let strings= words.match(srcReg);
if(strings && strings.length>0 && !list.includes(strings[0])){
list.push(strings[0])
}
})
}
return list ;
}
/*RGB颜色转换为16进制*/
static colorRbgToHex(rgbColor){
let lowerCaseColor = rgbColor.toLowerCase();
let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
if (/^(rgb|RGB)/.test(lowerCaseColor)) {
let aColor = lowerCaseColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
let strHex = "#";
for (let i=0; i<aColor.length; i++) {
let hex = Number(aColor[i]).toString(16);
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = lowerCaseColor;
}
return strHex;
} else if (reg.test(lowerCaseColor)) {
let aNum = lowerCaseColor.replace(/#/,"").split("");
if (aNum.length === 6) {
return lowerCaseColor;
} else if(aNum.length === 3) {
let numHex = "#";
for (let i=0; i<aNum.length; i+=1) {
numHex += (aNum[i] + aNum[i]);
}
return numHex;
}
}
return lowerCaseColor;
}
/**
*16进制颜色转为RGB格式
* @param hexColor 16进制颜色
* @returns {string} RGB格式颜色
*/
static colorHexToRgb(hexColor){
let sColor = hexColor.toLowerCase();
let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
let sColorNew = "#";
for (let i=1; i<4; i+=1) {
sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
}
sColor = sColorNew;
}
//处理六位的颜色值
let sColorChange = [];
for (let i=1; i<7; i+=2) {
sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
}
return "rgb(" + sColorChange.join(",") + ")";
}
return sColor;
};
/**
* 将整数部分逢三一断
* @param value
* @returns {string}
*/
static formatNumber(value) {
if (!value) {
return '0'
}
return value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
}
}
module.exports = StringHelper;
/**
* 获取跳转目标路径
* @param baseUrl
* @param params
* @returns {*}
*/
function getQueryUrl(baseUrl, params) {
let hasStartFlag = baseUrl.indexOf('?') !== -1
if (params instanceof Object) {
let requestUtl = baseUrl
for (let key in params) {
if (params[key] !== undefined) {
if (requestUtl.endsWith("?")) {
requestUtl = `${requestUtl}${key}=${params[key]}`
} else {
requestUtl = `${requestUtl}${!hasStartFlag ? '?' : '&'}${key}=${params[key]}`
if (!hasStartFlag) {
hasStartFlag = true
}
}
}
}
return requestUtl
} else {
return baseUrl
}
}
/**
* 从地址中截取参数
* @param url
* @returns {Map<any, any>}
*/
function getQueryMapFromUrl(url) {
const map = new Map()
if (url && url.indexOf("?") > 0) {
let paramsStr = url.substr(url.indexOf("?") + 1)
let groupList = paramsStr.split("&");
if (groupList && groupList.length > 0) {
groupList.forEach(item => {
let strings = item.split("=");
if (strings && strings.length > 1) {
map.set(strings[0], strings[1])
}
})
}
}
return map;
}
module.exports = {
getQueryMapFromUrl: getQueryMapFromUrl,
getQueryUrl: getQueryUrl,
};
let urlHelper = undefined;
let objectHelper = undefined;
let dateHelper = undefined;
let arrayHelper = undefined;
let calendarHelper = undefined;
let eventBus = undefined;
let stringHelper = undefined;
function getObjectHelper() {
if (objectHelper === undefined) {
objectHelper = require('./common/ObjectHelper')
}
return objectHelper;
}
function getUrlHelper() {
if (urlHelper === undefined) {
urlHelper = require('./common/UrlHelper')
}
return urlHelper;
}
function getDateHelper() {
if (dateHelper === undefined) {
dateHelper = require('./common/DateHelper')
}
return dateHelper;
}
function getCountDownTimer(millisInFuture, countDownInterval) {
let countDownTimer = require('./common/CountDownHelper');
return new countDownTimer(millisInFuture, countDownInterval);
}
function getArrayHelper() {
if (arrayHelper === undefined) {
arrayHelper = require('./common/ArrayHelper');
}
return arrayHelper;
}
function getCalendarHelper() {
if (calendarHelper === undefined) {
calendarHelper = require('./common/CalendarHelper')
}
return calendarHelper
}
function getStringHelper() {
if (stringHelper === undefined) {
stringHelper = require('./common/StringHelper')
}
return stringHelper
}
function getEventBus() {
if (eventBus === undefined) {
eventBus = require('./common/EventBus')
}
return eventBus;
}
class Common {
static getObjectHelper() {
return getObjectHelper();
}
static getUrlHelper() {
return getUrlHelper();
}
static getDateHelper() {
return getDateHelper();
}
static getCountDownTimer(millisInFuture, countDownInterval) {
return getCountDownTimer(millisInFuture, countDownInterval);
}
static getArrayHelper() {
return getArrayHelper();
}
static getStringHelper() {
return getStringHelper();
}
static getCalendarHelper() {
return getCalendarHelper();
}
static getEventBus() {
return getEventBus();
}
static dateConstants = require('./common/DateConstants');
static LogUtils = require('./common/LogUtils');
}
module.exports = Common;
{
"name": "compatible-tools",
"main": "index.d.ts"
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论