审计代码优化

This commit is contained in:
BianLzhaoMin 2024-08-30 17:45:46 +08:00
parent f00b9310bd
commit 8cfbf163c0
7 changed files with 1478 additions and 1222 deletions

View File

@ -4,11 +4,11 @@
* @param wait 延迟执行毫秒数
* @param immediate true - 立即执行 false - 延迟执行
*/
export const debounce = function(func, wait = 1000, immediate = true) {
export const debounce = function (func, wait = 1000, immediate = true) {
let timer;
console.log(1);
return function() {
console.log(123);
// console.log(1);
return function () {
// console.log(123);
let context = this,
args = arguments;
if (timer) clearTimeout(timer);
@ -21,10 +21,10 @@ export const debounce = function(func, wait = 1000, immediate = true) {
} else {
timer = setTimeout(() => {
func.apply(context, args);
}, wait)
}, wait);
}
}
}
};
};
/**
* @desc 函数节流
* @param func 函数
@ -34,7 +34,7 @@ export const debounce = function(func, wait = 1000, immediate = true) {
export const throttle = (func, wait = 1000, type = 1) => {
let previous = 0;
let timeout;
return function() {
return function () {
let context = this;
let args = arguments;
if (type === 1) {
@ -48,9 +48,9 @@ export const throttle = (func, wait = 1000, type = 1) => {
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
func.apply(context, args);
}, wait);
}
}
}
}
};
};

View File

@ -1,34 +1,28 @@
// 此版本发布于2023-03-27
const version = '2.0.36'
const version = "2.0.36";
// 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') {
console.log(`\n %c uView V${version} %c https://uviewui.com/ \n\n`, 'color: #ffffff; background: #3c9cff; padding:5px 0; border-radius: 5px;');
if (process.env.NODE_ENV === "development") {
// console.log(`\n %c uView V${version} %c https://uviewui.com/ \n\n`, 'color: #ffffff; background: #3c9cff; padding:5px 0; border-radius: 5px;');
}
export default {
v: version,
version,
// 主题名称
type: [
'primary',
'success',
'info',
'error',
'warning'
],
type: ["primary", "success", "info", "error", "warning"],
// 颜色部分本来可以通过scss的:export导出供js使用但是奈何nvue不支持
color: {
'u-primary': '#2979ff',
'u-warning': '#ff9900',
'u-success': '#19be6b',
'u-error': '#fa3534',
'u-info': '#909399',
'u-main-color': '#303133',
'u-content-color': '#606266',
'u-tips-color': '#909399',
'u-light-color': '#c0c4cc'
"u-primary": "#2979ff",
"u-warning": "#ff9900",
"u-success": "#19be6b",
"u-error": "#fa3534",
"u-info": "#909399",
"u-main-color": "#303133",
"u-content-color": "#606266",
"u-tips-color": "#909399",
"u-light-color": "#c0c4cc",
},
// 默认单位可以通过配置为rpx那么在用于传入组件大小参数为数值时就默认为rpx
unit: 'px'
}
unit: "px",
};

View File

@ -17,7 +17,7 @@ function strip(num, precision = 15) {
function digitLength(num) {
// Get digit length of e
const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0);
const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
return len > 0 ? len : 0;
}
@ -27,8 +27,8 @@ function digitLength(num) {
* @param {*number} num 输入数
*/
function float2Fixed(num) {
if (num.toString().indexOf('e') === -1) {
return Number(num.toString().replace('.', ''));
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
}
const dLen = digitLength(num);
return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
@ -42,7 +42,7 @@ function float2Fixed(num) {
function checkBoundary(num) {
if (_boundaryCheckingState) {
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
console.warn(`${num} 超出了精度限制,结果可能不正确`);
// console.warn(`${num} 超出了精度限制,结果可能不正确`);
}
}
}
@ -95,7 +95,10 @@ export function plus(...nums) {
const [num1, num2] = nums;
// 取最大的小数位
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
const baseNum = Math.pow(
10,
Math.max(digitLength(num1), digitLength(num2))
);
// 把小数都转为整数然后再计算
return (times(num1, baseNum) + times(num2, baseNum)) / baseNum;
}
@ -110,7 +113,10 @@ export function minus(...nums) {
}
const [num1, num2] = nums;
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
const baseNum = Math.pow(
10,
Math.max(digitLength(num1), digitLength(num2))
);
return (times(num1, baseNum) - times(num2, baseNum)) / baseNum;
}
@ -129,7 +135,10 @@ export function divide(...nums) {
checkBoundary(num1Changed);
checkBoundary(num2Changed);
// 重要这里必须用strip进行修正
return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1))));
return times(
num1Changed / num2Changed,
strip(Math.pow(10, digitLength(num2) - digitLength(num1)))
);
}
/**
@ -155,7 +164,6 @@ export function enableBoundaryChecking(flag = true) {
_boundaryCheckingState = flag;
}
export default {
times,
plus,
@ -164,4 +172,3 @@ export default {
round,
enableBoundaryChecking,
};

View File

@ -1,5 +1,5 @@
import test from './test.js'
import { round } from './digit.js'
import test from "./test.js";
import { round } from "./digit.js";
/**
* @description 如果value小于min取min如果value大于max取max
* @param {number} min
@ -7,7 +7,7 @@ import { round } from './digit.js'
* @param {number} value
*/
function range(min = 0, max = 0, value = 0) {
return Math.max(min, Math.min(max, Number(value)))
return Math.max(min, Math.min(max, Number(value)));
}
/**
@ -18,13 +18,15 @@ function range(min = 0, max = 0, value = 0) {
*/
function getPx(value, unit = false) {
if (test.number(value)) {
return unit ? `${value}px` : Number(value)
return unit ? `${value}px` : Number(value);
}
// 如果带有rpx先取出其数值部分再转为px值
if (/(rpx|upx)$/.test(value)) {
return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
return unit
? `${uni.upx2px(parseInt(value))}px`
: Number(uni.upx2px(parseInt(value)));
}
return unit ? `${parseInt(value)}px` : parseInt(value)
return unit ? `${parseInt(value)}px` : parseInt(value);
}
/**
@ -35,9 +37,9 @@ function getPx(value, unit = false) {
function sleep(value = 30) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, value)
})
resolve();
}, value);
});
}
/**
* @description 运行期判断平台
@ -45,14 +47,14 @@ function sleep(value = 30) {
* @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
*/
function os() {
return uni.getSystemInfoSync().platform.toLowerCase()
return uni.getSystemInfoSync().platform.toLowerCase();
}
/**
* @description 获取系统信息同步接口
* @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
*/
function sys() {
return uni.getSystemInfoSync()
return uni.getSystemInfoSync();
}
/**
@ -62,10 +64,10 @@ function sys() {
*/
function random(min, max) {
if (min >= 0 && max > 0 && max >= min) {
const gab = max - min + 1
return Math.floor(Math.random() * gab + min)
const gab = max - min + 1;
return Math.floor(Math.random() * gab + min);
}
return 0
return 0;
}
/**
@ -74,32 +76,36 @@ function random(min, max) {
* @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
*/
function guid(len = 32, firstU = true, radix = null) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = []
radix = radix || chars.length
const chars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
""
);
const uuid = [];
radix = radix || chars.length;
if (len) {
// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
for (let i = 0; i < len; i++)
uuid[i] = chars[0 | (Math.random() * radix)];
} else {
let r
let r;
// rfc4122标准要求返回的uuid中,某些位为固定的字符
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
uuid[14] = "4";
for (let i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
r = 0 | (Math.random() * 16);
uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
}
}
}
// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
if (firstU) {
uuid.shift()
return `u${uuid.join('')}`
uuid.shift();
return `u${uuid.join("")}`;
}
return uuid.join('')
return uuid.join("");
}
/**
@ -110,18 +116,18 @@ function guid(len = 32, firstU = true, radix = null) {
* @param {string|undefined} name 父组件的参数名
*/
function $parent(name = undefined) {
let parent = this.$parent
let parent = this.$parent;
// 通过while历遍这里主要是为了H5需要多层解析的问题
while (parent) {
// 父组件
if (parent.$options && parent.$options.name !== name) {
// 如果组件的name不相等继续上一级寻找
parent = parent.$parent
parent = parent.$parent;
} else {
return parent
return parent;
}
}
return false
return false;
}
/**
@ -131,38 +137,41 @@ function $parent(name = undefined) {
* @param {String} target 转换的目的object-转为对象string-转为字符串
* @returns {object|string}
*/
function addStyle(customStyle, target = 'object') {
function addStyle(customStyle, target = "object") {
// 字符串转字符串,对象转对象情形,直接返回
if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
typeof(customStyle) === 'string') {
return customStyle
if (
test.empty(customStyle) ||
(typeof customStyle === "object" && target === "object") ||
(target === "string" && typeof customStyle === "string")
) {
return customStyle;
}
// 字符串转对象
if (target === 'object') {
if (target === "object") {
// 去除字符串样式中的两端空格(中间的空格不能去掉比如padding: 20px 0如果去掉了就错了),空格是无用的
customStyle = trim(customStyle)
customStyle = trim(customStyle);
// 根据";"将字符串转为数组形式
const styleArray = customStyle.split(';')
const style = {}
const styleArray = customStyle.split(";");
const style = {};
// 历遍数组,拼接成对象
for (let i = 0; i < styleArray.length; i++) {
// 'font-size:20px;color:red;',如此最后字符串有";"的话会导致styleArray最后一个元素为空字符串这里需要过滤
if (styleArray[i]) {
const item = styleArray[i].split(':')
style[trim(item[0])] = trim(item[1])
const item = styleArray[i].split(":");
style[trim(item[0])] = trim(item[1]);
}
}
return style
return style;
}
// 这里为对象转字符串形式
let string = ''
let string = "";
for (const i in customStyle) {
// 驼峰转为中划线的形式否则css内联样式无法识别驼峰样式属性名
const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
string += `${key}:${customStyle[i]};`
const key = i.replace(/([A-Z])/g, "-$1").toLowerCase();
string += `${key}:${customStyle[i]};`;
}
// 去除两端空格
return trim(string)
return trim(string);
}
/**
@ -170,10 +179,10 @@ function addStyle(customStyle, target = 'object') {
* @param {string|number} value 需要添加单位的值
* @param {string} unit 添加的单位名 比如px
*/
function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') {
value = String(value)
function addUnit(value = "auto", unit = uni?.$u?.config?.unit ?? "px") {
value = String(value);
// 用uView内置验证规则中的number判断是否为数值
return test.number(value) ? `${value}${unit}` : value
return test.number(value) ? `${value}${unit}` : value;
}
/**
@ -183,7 +192,7 @@ function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') {
* @returns {*} 克隆后的对象或者原值不是对象
*/
function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj === null || typeof obj !== "object") return obj;
if (cache.has(obj)) return cache.get(obj);
let clone;
if (obj instanceof Date) {
@ -191,12 +200,14 @@ function deepClone(obj, cache = new WeakMap()) {
} else if (obj instanceof RegExp) {
clone = new RegExp(obj);
} else if (obj instanceof Map) {
clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]));
clone = new Map(
Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])
);
} else if (obj instanceof Set) {
clone = new Set(Array.from(obj, value => deepClone(value, cache)));
clone = new Set(Array.from(obj, (value) => deepClone(value, cache)));
} else if (Array.isArray(obj)) {
clone = obj.map(value => deepClone(value, cache));
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
clone = obj.map((value) => deepClone(value, cache));
} else if (Object.prototype.toString.call(obj) === "[object Object]") {
clone = Object.create(Object.getPrototypeOf(obj));
cache.set(obj, clone);
for (const [key, value] of Object.entries(obj)) {
@ -216,9 +227,17 @@ function deepClone(obj, cache = new WeakMap()) {
* @returns {object|boolean} 深度合并后的对象或者false入参有不是对象
*/
function deepMerge(target = {}, source = {}) {
target = deepClone(target)
if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target;
const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target);
target = deepClone(target);
if (
typeof target !== "object" ||
target === null ||
typeof source !== "object" ||
source === null
)
return target;
const merged = Array.isArray(target)
? target.slice()
: Object.assign({}, target);
for (const prop in source) {
if (!source.hasOwnProperty(prop)) continue;
const sourceValue = source[prop];
@ -231,7 +250,7 @@ function deepMerge(target = {}, source = {}) {
merged[prop] = new Map(sourceValue);
} else if (sourceValue instanceof Set) {
merged[prop] = new Set(sourceValue);
} else if (typeof sourceValue === 'object' && sourceValue !== null) {
} else if (typeof sourceValue === "object" && sourceValue !== null) {
merged[prop] = deepMerge(targetValue, sourceValue);
} else {
merged[prop] = sourceValue;
@ -246,8 +265,8 @@ function deepMerge(target = {}, source = {}) {
*/
function error(err) {
// 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') {
console.error(`uView提示${err}`)
if (process.env.NODE_ENV === "development") {
// console.error(`uView提示${err}`)
}
}
@ -258,33 +277,31 @@ function error(err) {
*/
function randomArray(array = []) {
// 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
return array.sort(() => Math.random() - 0.5)
return array.sort(() => Math.random() - 0.5);
}
// padStart 的 polyfill因为某些机型或情况还无法支持es7的padStart比如电脑版的微信小程序
// 所以这里做一个兼容polyfill的兼容处理
if (!String.prototype.padStart) {
// 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
String.prototype.padStart = function(maxLength, fillString = ' ') {
if (Object.prototype.toString.call(fillString) !== '[object String]') {
throw new TypeError(
'fillString must be String'
)
String.prototype.padStart = function (maxLength, fillString = " ") {
if (Object.prototype.toString.call(fillString) !== "[object String]") {
throw new TypeError("fillString must be String");
}
const str = this
const str = this;
// 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
if (str.length >= maxLength) return String(str)
if (str.length >= maxLength) return String(str);
const fillLength = maxLength - str.length
let times = Math.ceil(fillLength / fillString.length)
while (times >>= 1) {
fillString += fillString
const fillLength = maxLength - str.length;
let times = Math.ceil(fillLength / fillString.length);
while ((times >>= 1)) {
fillString += fillString;
if (times === 1) {
fillString += fillString
fillString += fillString;
}
}
return fillString.slice(0, fillLength) + str
}
return fillString.slice(0, fillLength) + str;
};
}
/**
@ -293,50 +310,57 @@ if (!String.prototype.padStart) {
* @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
* @returns {string} 返回格式化后的字符串
*/
function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
let date
function timeFormat(dateTime = null, formatStr = "yyyy-mm-dd") {
let date;
// 若传入时间为假值,则取当前时间
if (!dateTime) {
date = new Date()
date = new Date();
}
// 若为unix秒时间戳则转为毫秒时间戳逻辑有点奇怪但不敢改以保证历史兼容
else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
date = new Date(dateTime * 1000)
date = new Date(dateTime * 1000);
}
// 若用户传入字符串格式时间戳new Date无法解析需做兼容
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
date = new Date(Number(dateTime))
else if (typeof dateTime === "string" && /^\d+$/.test(dateTime.trim())) {
date = new Date(Number(dateTime));
}
// 处理平台性差异在Safari/Webkit中new Date仅支持/作为分割符的字符串时间
// 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
date = new Date(dateTime.replace(/-/g, '/'))
else if (
typeof dateTime === "string" &&
dateTime.includes("-") &&
!dateTime.includes("T")
) {
date = new Date(dateTime.replace(/-/g, "/"));
}
// 其他都认为符合 RFC 2822 规范
else {
date = new Date(dateTime)
date = new Date(dateTime);
}
const timeSource = {
'y': date.getFullYear().toString(), // 年
'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
'd': date.getDate().toString().padStart(2, '0'), // 日
'h': date.getHours().toString().padStart(2, '0'), // 时
'M': date.getMinutes().toString().padStart(2, '0'), // 分
's': date.getSeconds().toString().padStart(2, '0') // 秒
y: date.getFullYear().toString(), // 年
m: (date.getMonth() + 1).toString().padStart(2, "0"), // 月
d: date.getDate().toString().padStart(2, "0"), // 日
h: date.getHours().toString().padStart(2, "0"), // 时
M: date.getMinutes().toString().padStart(2, "0"), // 分
s: date.getSeconds().toString().padStart(2, "0"), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
}
};
for (const key in timeSource) {
const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
if (ret) {
// 年可能只需展示两位
const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
const beginIndex = key === "y" && ret.length === 2 ? 2 : 0;
formatStr = formatStr.replace(
ret,
timeSource[key].slice(beginIndex)
);
}
}
return formatStr
return formatStr;
}
/**
@ -347,41 +371,41 @@ if (!String.prototype.padStart) {
* 如果为布尔值false无论什么时间都返回多久以前的格式
* @returns {string} 转化后的内容
*/
function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
if (timestamp == null) timestamp = Number(new Date())
timestamp = parseInt(timestamp)
function timeFrom(timestamp = null, format = "yyyy-mm-dd") {
if (timestamp == null) timestamp = Number(new Date());
timestamp = parseInt(timestamp);
// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
if (timestamp.toString().length == 10) timestamp *= 1000
let timer = (new Date()).getTime() - timestamp
timer = parseInt(timer / 1000)
if (timestamp.toString().length == 10) timestamp *= 1000;
let timer = new Date().getTime() - timestamp;
timer = parseInt(timer / 1000);
// 如果小于5分钟,则返回"刚刚",其他以此类推
let tips = ''
let tips = "";
switch (true) {
case timer < 300:
tips = '刚刚'
break
tips = "刚刚";
break;
case timer >= 300 && timer < 3600:
tips = `${parseInt(timer / 60)}分钟前`
break
tips = `${parseInt(timer / 60)}分钟前`;
break;
case timer >= 3600 && timer < 86400:
tips = `${parseInt(timer / 3600)}小时前`
break
tips = `${parseInt(timer / 3600)}小时前`;
break;
case timer >= 86400 && timer < 2592000:
tips = `${parseInt(timer / 86400)}天前`
break
tips = `${parseInt(timer / 86400)}天前`;
break;
default:
// 如果format为false则无论什么时间戳都显示xx之前
if (format === false) {
if (timer >= 2592000 && timer < 365 * 86400) {
tips = `${parseInt(timer / (86400 * 30))}个月前`
tips = `${parseInt(timer / (86400 * 30))}个月前`;
} else {
tips = `${parseInt(timer / (86400 * 365))}年前`
tips = `${parseInt(timer / (86400 * 365))}年前`;
}
} else {
tips = timeFormat(timestamp, format)
tips = timeFormat(timestamp, format);
}
}
return tips
return tips;
}
/**
@ -389,21 +413,21 @@ function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
* @param String str 需要去除空格的字符串
* @param String pos both(左右)|left|right|all 默认both
*/
function trim(str, pos = 'both') {
str = String(str)
if (pos == 'both') {
return str.replace(/^\s+|\s+$/g, '')
function trim(str, pos = "both") {
str = String(str);
if (pos == "both") {
return str.replace(/^\s+|\s+$/g, "");
}
if (pos == 'left') {
return str.replace(/^\s*/, '')
if (pos == "left") {
return str.replace(/^\s*/, "");
}
if (pos == 'right') {
return str.replace(/(\s*$)/g, '')
if (pos == "right") {
return str.replace(/(\s*$)/g, "");
}
if (pos == 'all') {
return str.replace(/\s+/g, '')
if (pos == "all") {
return str.replace(/\s+/g, "");
}
return str
return str;
}
/**
@ -412,56 +436,57 @@ function trim(str, pos = 'both') {
* @param {Boolean} isPrefix,是否自动加上"?"
* @param {string} arrayFormat 规则 indices|brackets|repeat|comma
*/
function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
const prefix = isPrefix ? '?' : ''
const _result = []
if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
function queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") {
const prefix = isPrefix ? "?" : "";
const _result = [];
if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
arrayFormat = "brackets";
for (const key in data) {
const value = data[key]
const value = data[key];
// 去掉为空的参数
if (['', undefined, null].indexOf(value) >= 0) {
continue
if (["", undefined, null].indexOf(value) >= 0) {
continue;
}
// 如果值为数组,另行处理
if (value.constructor === Array) {
// e.g. {ids: [1, 2, 3]}
switch (arrayFormat) {
case 'indices':
case "indices":
// 结果: ids[0]=1&ids[1]=2&ids[2]=3
for (let i = 0; i < value.length; i++) {
_result.push(`${key}[${i}]=${value[i]}`)
_result.push(`${key}[${i}]=${value[i]}`);
}
break
case 'brackets':
break;
case "brackets":
// 结果: ids[]=1&ids[]=2&ids[]=3
value.forEach((_value) => {
_result.push(`${key}[]=${_value}`)
})
break
case 'repeat':
_result.push(`${key}[]=${_value}`);
});
break;
case "repeat":
// 结果: ids=1&ids=2&ids=3
value.forEach((_value) => {
_result.push(`${key}=${_value}`)
})
break
case 'comma':
_result.push(`${key}=${_value}`);
});
break;
case "comma":
// 结果: ids=1,2,3
let commaStr = ''
let commaStr = "";
value.forEach((_value) => {
commaStr += (commaStr ? ',' : '') + _value
})
_result.push(`${key}=${commaStr}`)
break
commaStr += (commaStr ? "," : "") + _value;
});
_result.push(`${key}=${commaStr}`);
break;
default:
value.forEach((_value) => {
_result.push(`${key}[]=${_value}`)
})
_result.push(`${key}[]=${_value}`);
});
}
} else {
_result.push(`${key}=${value}`)
_result.push(`${key}=${value}`);
}
}
return _result.length ? prefix + _result.join('&') : ''
return _result.length ? prefix + _result.join("&") : "";
}
/**
@ -472,9 +497,9 @@ function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
function toast(title, duration = 2000) {
uni.showToast({
title: String(title),
icon: 'none',
duration
})
icon: "none",
duration,
});
}
/**
@ -482,33 +507,34 @@ function toast(title, duration = 2000) {
* @param {String} type 主题名称,primary|info|error|warning|success
* @param {boolean} fill 是否使用fill填充实体的图标
*/
function type2icon(type = 'success', fill = false) {
function type2icon(type = "success", fill = false) {
// 如果非预置值,默认为success
if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success'
let iconName = ''
if (["primary", "info", "error", "warning", "success"].indexOf(type) == -1)
type = "success";
let iconName = "";
// 目前(2019-12-12),info和primary使用同一个图标
switch (type) {
case 'primary':
iconName = 'info-circle'
break
case 'info':
iconName = 'info-circle'
break
case 'error':
iconName = 'close-circle'
break
case 'warning':
iconName = 'error-circle'
break
case 'success':
iconName = 'checkmark-circle'
break
case "primary":
iconName = "info-circle";
break;
case "info":
iconName = "info-circle";
break;
case "error":
iconName = "close-circle";
break;
case "warning":
iconName = "error-circle";
break;
case "success":
iconName = "checkmark-circle";
break;
default:
iconName = 'checkmark-circle'
iconName = "checkmark-circle";
}
// 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
if (fill) iconName += '-fill'
return iconName
if (fill) iconName += "-fill";
return iconName;
}
/**
@ -519,25 +545,31 @@ function type2icon(type = 'success', fill = false) {
* @param {string} thousandsSeparator 千分位符号
* @returns {string} 格式化后的数字
*/
function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
number = (`${number}`).replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator
const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint
let s = ''
function priceFormat(
number,
decimals = 0,
decimalPoint = ".",
thousandsSeparator = ","
) {
number = `${number}`.replace(/[^0-9+-Ee.]/g, "");
const n = !isFinite(+number) ? 0 : +number;
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
const sep =
typeof thousandsSeparator === "undefined" ? "," : thousandsSeparator;
const dec = typeof decimalPoint === "undefined" ? "." : decimalPoint;
let s = "";
s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.')
const re = /(-?\d+)(\d{3})/
s = (prec ? round(n, prec) + "" : `${Math.round(n)}`).split(".");
const re = /(-?\d+)(\d{3})/;
while (re.test(s[0])) {
s[0] = s[0].replace(re, `$1${sep}$2`)
s[0] = s[0].replace(re, `$1${sep}$2`);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
if ((s[1] || "").length < prec) {
s[1] = s[1] || "";
s[1] += new Array(prec - s[1].length + 1).join("0");
}
return s.join(dec)
return s.join(dec);
}
/**
@ -549,14 +581,14 @@ function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparato
* @return {string|number}
*/
function getDuration(value, unit = true) {
const valueNum = parseInt(value)
const valueNum = parseInt(value);
if (unit) {
if (/s$/.test(value)) return value
return value > 30 ? `${value}ms` : `${value}s`
if (/s$/.test(value)) return value;
return value > 30 ? `${value}ms` : `${value}s`;
}
if (/ms$/.test(value)) return valueNum
if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000
return valueNum
if (/ms$/.test(value)) return valueNum;
if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000;
return valueNum;
}
/**
@ -564,7 +596,7 @@ function getDuration(value, unit = true) {
* @param {String} value 需要补零的值
*/
function padZero(value) {
return `00${value}`.slice(-2)
return `00${value}`.slice(-2);
}
/**
@ -573,12 +605,12 @@ function padZero(value) {
* @param {*} event
*/
function formValidate(instance, event) {
const formItem = uni.$u.$parent.call(instance, 'u-form-item')
const form = uni.$u.$parent.call(instance, 'u-form')
const formItem = uni.$u.$parent.call(instance, "u-form-item");
const form = uni.$u.$parent.call(instance, "u-form");
// 如果发生变化的input或者textarea等其父组件中有u-form-item或者u-form等就执行form的validate方法
// 同时将form-item的pros传递给form让其进行精确对象验证
if (formItem && form) {
form.validateField(formItem.prop, () => {}, event)
form.validateField(formItem.prop, () => {}, event);
}
}
@ -590,23 +622,23 @@ function formValidate(instance, event) {
*/
function getProperty(obj, key) {
if (!obj) {
return
return;
}
if (typeof key !== 'string' || key === '') {
return ''
if (typeof key !== "string" || key === "") {
return "";
}
if (key.indexOf('.') !== -1) {
const keys = key.split('.')
let firstObj = obj[keys[0]] || {}
if (key.indexOf(".") !== -1) {
const keys = key.split(".");
let firstObj = obj[keys[0]] || {};
for (let i = 1; i < keys.length; i++) {
if (firstObj) {
firstObj = firstObj[keys[i]]
firstObj = firstObj[keys[i]];
}
}
return firstObj
return firstObj;
}
return obj[key]
return obj[key];
}
/**
@ -617,34 +649,34 @@ function getProperty(obj, key) {
*/
function setProperty(obj, key, value) {
if (!obj) {
return
return;
}
// 递归赋值
const inFn = function(_obj, keys, v) {
const inFn = function (_obj, keys, v) {
// 最后一个属性key
if (keys.length === 1) {
_obj[keys[0]] = v
return
_obj[keys[0]] = v;
return;
}
// 0~length-1个key
while (keys.length > 1) {
const k = keys[0]
if (!_obj[k] || (typeof _obj[k] !== 'object')) {
_obj[k] = {}
const k = keys[0];
if (!_obj[k] || typeof _obj[k] !== "object") {
_obj[k] = {};
}
const key = keys.shift()
const key = keys.shift();
// 自调用判断是否存在属性,不存在则自动创建对象
inFn(_obj[k], keys, v)
}
inFn(_obj[k], keys, v);
}
};
if (typeof key !== 'string' || key === '') {
} else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作
const keys = key.split('.')
inFn(obj, keys, value)
if (typeof key !== "string" || key === "") {
} else if (key.indexOf(".") !== -1) {
// 支持多层级赋值操作
const keys = key.split(".");
inFn(obj, keys, value);
} else {
obj[key] = value
obj[key] = value;
}
}
@ -652,17 +684,17 @@ function setProperty(obj, key, value) {
* @description 获取当前页面路径
*/
function page() {
const pages = getCurrentPages()
const pages = getCurrentPages();
// 某些特殊情况下(比如页面进行redirectTo时的一些时机)pages可能为空数组
return `/${pages[pages.length - 1]?.route ?? ''}`
return `/${pages[pages.length - 1]?.route ?? ""}`;
}
/**
* @description 获取当前路由栈实例数组
*/
function pages() {
const pages = getCurrentPages()
return pages
const pages = getCurrentPages();
return pages;
}
/**
@ -670,9 +702,9 @@ function pages() {
* @param back {number} [0] - 0或者负数表示获取历史栈的哪一层0表示获取当前页面实例-1 表示获取上一个页面实例默认0
*/
function getHistoryPage(back = 0) {
const pages = getCurrentPages()
const len = pages.length
return pages[len - 1 + back]
const pages = getCurrentPages();
const len = pages.length;
return pages[len - 1 + back];
}
/**
@ -682,19 +714,12 @@ function getHistoryPage(back = 0) {
* @param {object} color 修改内置color属性
* @param {object} zIndex 修改内置zIndex属性
*/
function setConfig({
props = {},
config = {},
color = {},
zIndex = {}
}) {
const {
deepMerge,
} = uni.$u
uni.$u.config = deepMerge(uni.$u.config, config)
uni.$u.props = deepMerge(uni.$u.props, props)
uni.$u.color = deepMerge(uni.$u.color, color)
uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex)
function setConfig({ props = {}, config = {}, color = {}, zIndex = {} }) {
const { deepMerge } = uni.$u;
uni.$u.config = deepMerge(uni.$u.config, config);
uni.$u.props = deepMerge(uni.$u.props, props);
uni.$u.color = deepMerge(uni.$u.color, color);
uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex);
}
export default {
@ -727,5 +752,5 @@ export default {
page,
pages,
getHistoryPage,
setConfig
}
setConfig,
};

View File

@ -11,12 +11,12 @@
* HBuilderX: beat-3.0.4 alpha-3.0.4
*/
import dispatchRequest from './dispatchRequest'
import InterceptorManager from './InterceptorManager'
import mergeConfig from './mergeConfig'
import defaults from './defaults'
import { isPlainObject } from '../utils'
import clone from '../utils/clone'
import dispatchRequest from "./dispatchRequest";
import InterceptorManager from "./InterceptorManager";
import mergeConfig from "./mergeConfig";
import defaults from "./defaults";
import { isPlainObject } from "../utils";
import clone from "../utils/clone";
export default class Request {
/**
@ -35,14 +35,14 @@ export default class Request {
*/
constructor(arg = {}) {
if (!isPlainObject(arg)) {
arg = {}
console.warn('设置全局参数必须接收一个Object')
arg = {};
// console.warn('设置全局参数必须接收一个Object')
}
this.config = clone({ ...defaults, ...arg })
this.config = clone({ ...defaults, ...arg });
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
}
response: new InterceptorManager(),
};
}
/**
@ -50,27 +50,27 @@ export default class Request {
* @param {Request~setConfigCallback} f - 设置全局默认配置
*/
setConfig(f) {
this.config = f(this.config)
this.config = f(this.config);
}
middleware(config) {
config = mergeConfig(this.config, config)
const chain = [dispatchRequest, undefined]
let promise = Promise.resolve(config)
config = mergeConfig(this.config, config);
const chain = [dispatchRequest, undefined];
let promise = Promise.resolve(config);
this.interceptors.request.forEach((interceptor) => {
chain.unshift(interceptor.fulfilled, interceptor.rejected)
})
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach((interceptor) => {
chain.push(interceptor.fulfilled, interceptor.rejected)
})
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift())
promise = promise.then(chain.shift(), chain.shift());
}
return promise
return promise;
}
/**
@ -85,24 +85,24 @@ export default class Request {
* @returns {Promise<unknown>}
*/
request(config = {}) {
return this.middleware(config)
return this.middleware(config);
}
get(url, options = {}) {
return this.middleware({
url,
method: 'GET',
...options
})
method: "GET",
...options,
});
}
post(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'POST',
...options
})
method: "POST",
...options,
});
}
// #ifndef MP-ALIPAY
@ -110,9 +110,9 @@ export default class Request {
return this.middleware({
url,
data,
method: 'PUT',
...options
})
method: "PUT",
...options,
});
}
// #endif
@ -122,9 +122,9 @@ export default class Request {
return this.middleware({
url,
data,
method: 'DELETE',
...options
})
method: "DELETE",
...options,
});
}
// #endif
@ -134,9 +134,9 @@ export default class Request {
return this.middleware({
url,
data,
method: 'CONNECT',
...options
})
method: "CONNECT",
...options,
});
}
// #endif
@ -146,9 +146,9 @@ export default class Request {
return this.middleware({
url,
data,
method: 'HEAD',
...options
})
method: "HEAD",
...options,
});
}
// #endif
@ -158,9 +158,9 @@ export default class Request {
return this.middleware({
url,
data,
method: 'OPTIONS',
...options
})
method: "OPTIONS",
...options,
});
}
// #endif
@ -170,23 +170,23 @@ export default class Request {
return this.middleware({
url,
data,
method: 'TRACE',
...options
})
method: "TRACE",
...options,
});
}
// #endif
upload(url, config = {}) {
config.url = url
config.method = 'UPLOAD'
return this.middleware(config)
config.url = url;
config.method = "UPLOAD";
return this.middleware(config);
}
download(url, config = {}) {
config.url = url
config.method = 'DOWNLOAD'
return this.middleware(config)
config.url = url;
config.method = "DOWNLOAD";
return this.middleware(config);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
export class Mcaptcha {
constructor(options) {
this.options = options;
this.fontSize = options.height * 3 / 6;
this.fontSize = (options.height * 3) / 6;
this.init();
this.refresh();
}
@ -13,17 +13,80 @@ export class Mcaptcha {
this.ctx.setFillStyle(this.randomColor(180, 240));
}
refresh() {
var code = '';
var txtArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var code = "";
var txtArr = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
];
for (var i = 0; i < 4; i++) {
code += txtArr[this.randomNum(0, txtArr.length)];
}
this.options.createCodeImg = code;
let arr = (code + '').split('');
let arr = (code + "").split("");
if (arr.length === 0) {
arr = ['e', 'r', 'r', 'o', 'r'];
};
let offsetLeft = this.options.width * 0.6 / (arr.length - 1);
arr = ["e", "r", "r", "o", "r"];
}
let offsetLeft = (this.options.width * 0.6) / (arr.length - 1);
let marginLeft = this.options.width * 0.2;
arr.forEach((item, index) => {
this.ctx.setFillStyle(this.randomColor(0, 180));
@ -32,22 +95,34 @@ export class Mcaptcha {
let dis = offsetLeft * index + marginLeft - size * 0.3;
let deg = this.randomNum(-30, 30);
this.ctx.translate(dis, this.options.height * 0.5);
this.ctx.rotate(deg * Math.PI / 180);
this.ctx.rotate((deg * Math.PI) / 180);
this.ctx.fillText(item, 0, 0);
this.ctx.rotate(-deg * Math.PI / 180);
this.ctx.rotate((-deg * Math.PI) / 180);
this.ctx.translate(-dis, -this.options.height * 0.5);
})
});
for (var i = 0; i < 4; i++) {
this.ctx.strokeStyle = this.randomColor(40, 180);
this.ctx.beginPath();
this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
this.ctx.moveTo(
this.randomNum(0, this.options.width),
this.randomNum(0, this.options.height)
);
this.ctx.lineTo(
this.randomNum(0, this.options.width),
this.randomNum(0, this.options.height)
);
this.ctx.stroke();
}
for (var i = 0; i < this.options.width / 4; i++) {
this.ctx.fillStyle = this.randomColor(0, 255);
this.ctx.beginPath();
this.ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
this.ctx.arc(
this.randomNum(0, this.options.width),
this.randomNum(0, this.options.height),
1,
0,
2 * Math.PI
);
this.ctx.fill();
}
this.ctx.draw();
@ -55,8 +130,8 @@ export class Mcaptcha {
validate(code) {
var code = code.toLowerCase();
var v_code = this.options.createCodeImg.toLowerCase();
console.log(code)
console.log(v_code.substring(v_code.length - 4))
// console.log(code)
// console.log(v_code.substring(v_code.length - 4))
if (code == v_code.substring(v_code.length - 4)) {
return true;
} else {