Browse Source

KERNEL-13991 feat: core/func文件夹

es6
zsmj 2 years ago
parent
commit
8ed5aaf502
  1. 171
      src/core/func/alias.js
  2. 84
      src/core/func/date.js
  3. 36
      src/core/func/function.js
  4. 34
      src/core/func/number.js
  5. 14
      src/core/func/string.js

171
src/core/func/alias.js

@ -2,7 +2,7 @@ import {each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseD
import {replaceAll} from "./string"; import {replaceAll} from "./string";
import {getFullDayName, getMonthName, getTimezone} from "./date"; import {getFullDayName, getMonthName, getTimezone} from "./date";
var _global; let _global;
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
_global = window; _global = window;
} else if (typeof global !== "undefined") { } else if (typeof global !== "undefined") {
@ -47,12 +47,12 @@ function _eFormat(text, fmt) {
* @returns {*} * @returns {*}
*/ */
function eFormat(num, format) { function eFormat(num, format) {
var neg = num < 0 ? (num *= -1, "-") : "", let neg = num < 0 ? (num *= -1, "-") : "",
magnitudeNeg = ""; magnitudeNeg = "";
var funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 const funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1
// 数量级 // 数量级
var magnitude = Math[funcName](Math.log(num) / Math.log(10)); let magnitude = Math[funcName](Math.log(num) / Math.log(10));
if (!isFinite(magnitude)) { if (!isFinite(magnitude)) {
return format.replace(/#/ig, "").replace(/\.e/ig, "E"); return format.replace(/#/ig, "").replace(/\.e/ig, "E");
@ -67,15 +67,15 @@ function _eFormat(text, fmt) {
} }
// 计算出format中需要显示的整数部分的位数,然后更新这个数值,也更新数量级 // 计算出format中需要显示的整数部分的位数,然后更新这个数值,也更新数量级
var integerLen = getInteger(magnitude, format); const integerLen = getInteger(magnitude, format);
integerLen > 1 && (magnitude -= integerLen - 1, num *= Math.pow(10, integerLen - 1)); integerLen > 1 && (magnitude -= integerLen - 1, num *= Math.pow(10, integerLen - 1));
magnitude < 0 && (magnitudeNeg = "-", magnitude *= -1); magnitude < 0 && (magnitudeNeg = "-", magnitude *= -1);
// 获取科学计数法精确到的位数 // 获取科学计数法精确到的位数
var precision = getPrecision(format); const precision = getPrecision(format);
// 判断num经过四舍五入之后是否有进位 // 判断num经过四舍五入之后是否有进位
var isValueCarry = isValueCarried(num); const isValueCarry = isValueCarried(num);
num *= Math.pow(10, precision); num *= Math.pow(10, precision);
num = Math.round(num); num = Math.round(num);
@ -104,8 +104,8 @@ function _eFormat(text, fmt) {
} }
// 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了
var isAllZero = true; let isAllZero = true;
for (var i = 0, len = num.length; i < len; i++) { for (let i = 0, len = num.length; i < len; i++) {
if (!isAllZero) { if (!isAllZero) {
continue; continue;
} }
@ -121,7 +121,7 @@ function _eFormat(text, fmt) {
if (!/e/ig.test(format)) { if (!/e/ig.test(format)) {
return 0; return 0;
} }
var arr = format.split(/e/ig)[0].split("."); const arr = format.split(/e/ig)[0].split(".");
return arr.length > 1 ? arr[1].length : 0; return arr.length > 1 ? arr[1].length : 0;
} }
@ -134,8 +134,8 @@ function _eFormat(text, fmt) {
} }
// return format.split(/e/ig)[0].split(".")[0].length; // return format.split(/e/ig)[0].split(".")[0].length;
var formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length; let formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length;
var valueLeftLen = 0; let valueLeftLen = 0;
for (i = 0; i < len; i++) { for (i = 0; i < len; i++) {
f = formatLeft.charAt(i); f = formatLeft.charAt(i);
@ -150,7 +150,7 @@ function _eFormat(text, fmt) {
// 判断num通过round函数之后是否有进位 // 判断num通过round函数之后是否有进位
function isValueCarried(num) { function isValueCarried(num) {
var roundNum = Math.round(num); let roundNum = Math.round(num);
num = (num + "").split(".")[0]; num = (num + "").split(".")[0];
roundNum = (roundNum + "").split(".")[0]; roundNum = (roundNum + "").split(".")[0];
return num.length !== roundNum.length; return num.length !== roundNum.length;
@ -160,13 +160,13 @@ function _eFormat(text, fmt) {
//'#.##'之类的格式处理 1.324e-18 这种的科学数字 //'#.##'之类的格式处理 1.324e-18 这种的科学数字
function _dealNumberPrecision(text, fright) { function _dealNumberPrecision(text, fright) {
if (/[eE]/.test(text)) { if (/[eE]/.test(text)) {
var precision = 0, i = 0, ch; let precision = 0, i = 0, ch;
if (/[%‰]$/.test(fright)) { if (/[%‰]$/.test(fright)) {
precision = /[%]$/.test(fright) ? 2 : 3; precision = /[%]$/.test(fright) ? 2 : 3;
} }
for (var len = fright.length; i < len; i++) { for (let len = fright.length; i < len; i++) {
if ((ch = fright.charAt(i)) == "0" || ch == "#") { if ((ch = fright.charAt(i)) == "0" || ch == "#") {
precision++; precision++;
} }
@ -181,7 +181,7 @@ function _dealNumberPrecision(text, fright) {
* 数字格式 * 数字格式
*/ */
function _numberFormat(text, format) { function _numberFormat(text, format) {
var text = text + ""; text = text + "";
//在调用数字格式的时候如果text里没有任何数字则不处理 //在调用数字格式的时候如果text里没有任何数字则不处理
if (!(/[0-9]/.test(text)) || !format) { if (!(/[0-9]/.test(text)) || !format) {
@ -189,7 +189,7 @@ function _numberFormat(text, format) {
} }
// 数字格式,区分正负数 // 数字格式,区分正负数
var numMod = format.indexOf(";"); const numMod = format.indexOf(";");
if (numMod > -1) { if (numMod > -1) {
if (text >= 0) { if (text >= 0) {
return _numberFormat(text + "", format.substring(0, numMod)); return _numberFormat(text + "", format.substring(0, numMod));
@ -203,19 +203,19 @@ function _numberFormat(text, format) {
} }
} }
var fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || ""; const fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || "";
text = _dealNumberPrecision(text, fright); text = _dealNumberPrecision(text, fright);
var tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || ""; let tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || "";
// 百分比,千分比的小数点移位处理 // 百分比,千分比的小数点移位处理
if (/[%‰]$/.test(format)) { if (/[%‰]$/.test(format)) {
var paddingZero = /[%]$/.test(format) ? "00" : "000"; let paddingZero = /[%]$/.test(format) ? "00" : "000";
tright += paddingZero; tright += paddingZero;
tleft += tright.substring(0, paddingZero.length); tleft += tright.substring(0, paddingZero.length);
tleft = tleft.replace(/^0+/gi, ""); tleft = tleft.replace(/^0+/gi, "");
tright = tright.substring(paddingZero.length).replace(/0+$/gi, ""); tright = tright.substring(paddingZero.length).replace(/0+$/gi, "");
} }
var right = _dealWithRight(tright, fright); let right = _dealWithRight(tright, fright);
if (right.leftPlus) { if (right.leftPlus) {
// 小数点后有进位 // 小数点后有进位
tleft = parseInt(tleft) + 1 + ""; tleft = parseInt(tleft) + 1 + "";
@ -223,7 +223,7 @@ function _numberFormat(text, format) {
tleft = isNaN(tleft) ? "1" : tleft; tleft = isNaN(tleft) ? "1" : tleft;
} }
right = right.num; right = right.num;
var left = _dealWithLeft(tleft, fleft); let left = _dealWithLeft(tleft, fleft);
if (!(/[0-9]/.test(left))) { if (!(/[0-9]/.test(left))) {
left = left + "0"; left = left + "0";
} }
@ -242,10 +242,10 @@ function _numberFormat(text, format) {
* @private * @private
*/ */
function _dealWithRight(tright, fright) { function _dealWithRight(tright, fright) {
var right = "", j = 0, i = 0; let right = "", j = 0, i = 0;
for (var len = fright.length; i < len; i++) { for (let len = fright.length; i < len; i++) {
var ch = fright.charAt(i); const ch = fright.charAt(i);
var c = tright.charAt(j); let c = tright.charAt(j);
switch (ch) { switch (ch) {
case "0": case "0":
if (isEmpty(c)) { if (isEmpty(c)) {
@ -263,16 +263,16 @@ function _dealWithRight(tright, fright) {
break; break;
} }
} }
var rll = tright.substring(j); const rll = tright.substring(j);
var result = {}; const result = {};
if (!isEmpty(rll) && rll.charAt(0) > 4) { if (!isEmpty(rll) && rll.charAt(0) > 4) {
// 有多余字符,需要四舍五入 // 有多余字符,需要四舍五入
result.leftPlus = true; result.leftPlus = true;
var numReg = right.match(/^[0-9]+/); const numReg = right.match(/^[0-9]+/);
if (numReg) { if (numReg) {
var num = numReg[0]; const num = numReg[0];
var orilen = num.length; const orilen = num.length;
var newnum = parseInt(num) + 1 + ""; let newnum = parseInt(num) + 1 + "";
// 进位到整数部分 // 进位到整数部分
if (newnum.length > orilen) { if (newnum.length > orilen) {
newnum = newnum.substring(1); newnum = newnum.substring(1);
@ -295,13 +295,14 @@ function _dealWithRight(tright, fright) {
* @private * @private
*/ */
function _dealWithLeft(tleft, fleft) { function _dealWithLeft(tleft, fleft) {
var left = ""; let newstr;
var j = tleft.length - 1; let left = "";
var combo = -1, last = -1; let j = tleft.length - 1;
var i = fleft.length - 1; let combo = -1, last = -1;
let i = fleft.length - 1;
for (; i >= 0; i--) { for (; i >= 0; i--) {
var ch = fleft.charAt(i); const ch = fleft.charAt(i);
var c = tleft.charAt(j); let c = tleft.charAt(j);
switch (ch) { switch (ch) {
case "0": case "0":
if (isEmpty(c)) { if (isEmpty(c)) {
@ -319,7 +320,7 @@ function _dealWithLeft(tleft, fleft) {
case ",": case ",":
if (!isEmpty(c)) { if (!isEmpty(c)) {
// 计算一个,分隔区间的长度 // 计算一个,分隔区间的长度
var com = fleft.match(/,[#0]+/); const com = fleft.match(/,[#0]+/);
if (com) { if (com) {
combo = com[0].length - 1; combo = com[0].length - 1;
} }
@ -333,19 +334,20 @@ function _dealWithLeft(tleft, fleft) {
} }
if (last > -1) { if (last > -1) {
// 处理剩余字符 // 处理剩余字符
var tll = tleft.substring(0, j + 1); const tll = tleft.substring(0, j + 1);
left = left.substring(0, last) + tll + left.substring(last); left = left.substring(0, last) + tll + left.substring(last);
} }
if (combo > 0) { if (combo > 0) {
// 处理,分隔区间 // 处理,分隔区间
var res = left.match(/[0-9]+,/); let res = left.match(/[0-9]+,/);
if (res) { if (res) {
res = res[0]; res = res[0];
var newstr = "", n = res.length - 1 - combo; newstr = "";
let n = res.length - 1 - combo;
for (; n >= 0; n = n - combo) { for (; n >= 0; n = n - combo) {
newstr = res.substring(n, combo) + "," + newstr; newstr = res.substring(n, combo) + "," + newstr;
} }
var lres = res.substring(0, n + combo); const lres = res.substring(0, n + combo);
if (!isEmpty(lres)) { if (!isEmpty(lres)) {
newstr = lres + "," + newstr; newstr = lres + "," + newstr;
} }
@ -361,9 +363,9 @@ export const cjkEncode = function (text) {
return text; return text;
} }
var newText = ""; let newText = "";
for (var i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
var code = text.charCodeAt(i); const code = text.charCodeAt(i);
if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]". if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]".
newText += "[" + code.toString(16) + "]"; newText += "[" + code.toString(16) + "]";
} else { } else {
@ -386,17 +388,17 @@ export const cjkDecode = function (text) {
return ""; return "";
} }
// 查找没有 "[", 直接返回. kunsnat:数字的时候, 不支持indexOf方法, 也是直接返回. // 查找没有 "[", 直接返回. kunsnat:数字的时候, 不支持indexOf方法, 也是直接返回.
if (!isNaN(text) || text.indexOf("[") == -1) { if (!isNaN(text) || text.indexOf("[") === -1) {
return text; return text;
} }
var newText = ""; let newText = "";
for (var i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
var ch = text.charAt(i); let ch = text.charAt(i);
if (ch == "[") { if (ch === "[") {
var rightIdx = text.indexOf("]", i + 1); const rightIdx = text.indexOf("]", i + 1);
if (rightIdx > i + 1) { if (rightIdx > i + 1) {
var subText = text.substring(i + 1, rightIdx); let subText = text.substring(i + 1, rightIdx);
// james:主要是考虑[CDATA[]]这样的值的出现 // james:主要是考虑[CDATA[]]这样的值的出现
if (subText.length > 0) { if (subText.length > 0) {
ch = String.fromCharCode(eval("0x" + subText)); ch = String.fromCharCode(eval("0x" + subText));
@ -419,7 +421,7 @@ const SPECIAL_TAGS = {
"<": "&lt;", "<": "&lt;",
">": "&gt;", ">": "&gt;",
"\x20": "&nbsp;", "\x20": "&nbsp;",
"\n": "&#10;" "\n": "&#10;",
}; };
export const htmlEncode = function (text) { export const htmlEncode = function (text) {
return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) { return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) {
@ -450,7 +452,7 @@ export const htmlDecode = function (text) {
export const cjkEncodeDO = function (o) { export const cjkEncodeDO = function (o) {
if (isPlainObject(o)) { if (isPlainObject(o)) {
var result = {}; let result = {};
each(o, function (v, k) { each(o, function (v, k) {
if (!(typeof v === "string")) { if (!(typeof v === "string")) {
v = jsonEncode(v); v = jsonEncode(v);
@ -466,25 +468,25 @@ export const cjkEncodeDO = function (o) {
export const jsonEncode = function (o) { export const jsonEncode = function (o) {
// james:这个Encode是抄的EXT的 // james:这个Encode是抄的EXT的
var useHasOwn = !!{}.hasOwnProperty; let useHasOwn = !!{}.hasOwnProperty;
// crashes Safari in some instances // crashes Safari in some instances
// var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; // var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
var m = { let m = {
"\b": "\\b", "\b": "\\b",
"\t": "\\t", "\t": "\\t",
"\n": "\\n", "\n": "\\n",
"\f": "\\f", "\f": "\\f",
"\r": "\\r", "\r": "\\r",
"\"": "\\\"", "\"": "\\\"",
"\\": "\\\\" "\\": "\\\\",
}; };
var encodeString = function (s) { let encodeString = function (s) {
if (/["\\\x00-\x1f]/.test(s)) { if (/["\\\x00-\x1f]/.test(s)) {
return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) {
var c = m[b]; let c = m[b];
if (c) { if (c) {
return c; return c;
} }
@ -497,8 +499,8 @@ export const jsonEncode = function (o) {
return "\"" + s + "\""; return "\"" + s + "\"";
}; };
var encodeArray = function (o) { let encodeArray = function (o) {
var a = ["["], b, i, l = o.length, v; let a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) { for (i = 0; i < l; i += 1) {
v = o[i]; v = o[i];
switch (typeof v) { switch (typeof v) {
@ -528,7 +530,7 @@ export const jsonEncode = function (o) {
* 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下 * 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下
*/ */
return jsonEncode({ return jsonEncode({
__time__: o.getTime() __time__: o.getTime(),
}); });
} else if (typeof o === "string") { } else if (typeof o === "string") {
return encodeString(o); return encodeString(o);
@ -539,7 +541,7 @@ export const jsonEncode = function (o) {
} else if (isFunction(o)) { } else if (isFunction(o)) {
return String(o); return String(o);
} }
var a = ["{"], b, i, v; let a = ["{"], b, i, v;
for (i in o) { for (i in o) {
if (!useHasOwn || o.hasOwnProperty(i)) { if (!useHasOwn || o.hasOwnProperty(i)) {
v = o[i]; v = o[i];
@ -564,8 +566,9 @@ export const jsonEncode = function (o) {
export const jsonDecode = function (text) { export const jsonDecode = function (text) {
let jo;
try { try {
var jo = JSON.parse(text); jo = JSON.parse(text);
if (jo == null) { if (jo == null) {
jo = {}; jo = {};
} }
@ -601,8 +604,8 @@ export const jsonDecode = function (text) {
if (o && o.__time__ != null) { if (o && o.__time__ != null) {
return new Date(o.__time__); return new Date(o.__time__);
} }
for (var a in o) { for (const a in o) {
if (o[a] == o || typeof o[a] === "object" || isFunction(o[a])) { if (o[a] === o || typeof o[a] === "object" || isFunction(o[a])) {
break; break;
} }
o[a] = parse(o[a]); o[a] = parse(o[a]);
@ -641,7 +644,7 @@ export const encodeURIComponent = function (url) {
}; };
export const decodeURIComponent = function (url) { export const decodeURIComponent = function (url) {
var reserveSpecialCharsMap = {}; const reserveSpecialCharsMap = {};
each(BI.specialCharsMap, function (initialChar, encodeChar) { each(BI.specialCharsMap, function (initialChar, encodeChar) {
reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar;
}); });
@ -657,7 +660,7 @@ export const contentFormat = function (cv, fmt) {
// 原值为空,返回空字符 // 原值为空,返回空字符
return ""; return "";
} }
var text = cv.toString(); let text = cv.toString();
if (isEmpty(fmt)) { if (isEmpty(fmt)) {
// 格式为空,返回原字符 // 格式为空,返回原字符
return text; return text;
@ -677,7 +680,7 @@ export const contentFormat = function (cv, fmt) {
} }
} }
if (!isInvalidDate(cv) && !isNull(cv)) { if (!isInvalidDate(cv) && !isNull(cv)) {
var needTrim = fmt.match(/^DT/); const needTrim = fmt.match(/^DT/);
text = date2Str(cv, fmt.substring(needTrim ? 2 : 1)); text = date2Str(cv, fmt.substring(needTrim ? 2 : 1));
} }
} else if (fmt.match(/E/)) { } else if (fmt.match(/E/)) {
@ -749,7 +752,7 @@ export const str2Date = function (str, format) {
if (typeof str != "string" || typeof format != "string") { if (typeof str != "string" || typeof format != "string") {
return null; return null;
} }
var fmt = parseFmt(format); const fmt = parseFmt(format);
return parseDateTime(str, fmt); return parseDateTime(str, fmt);
}; };
@ -767,16 +770,16 @@ export const date2Str = function (date, format) {
return ""; return "";
} }
// O(len(format)) // O(len(format))
var len = format.length, result = ""; let len = format.length, result = "";
if (len > 0) { if (len > 0) {
var flagch = format.charAt(0), start = 0, str = flagch; let flagch = format.charAt(0), start = 0, str = flagch;
for (var i = 1; i < len; i++) { for (let i = 1; i < len; i++) {
var ch = format.charAt(i); const ch = format.charAt(i);
if (flagch !== ch) { if (flagch !== ch) {
result += compileJFmt({ result += compileJFmt({
char: flagch, char: flagch,
str: str, str: str,
len: i - start len: i - start,
}, date); }, date);
flagch = ch; flagch = ch;
start = i; start = i;
@ -788,13 +791,13 @@ export const date2Str = function (date, format) {
result += compileJFmt({ result += compileJFmt({
char: flagch, char: flagch,
str: str, str: str,
len: len - start len: len - start,
}, date); }, date);
} }
return result; return result;
function compileJFmt(jfmt, date) { function compileJFmt(jfmt, date) {
var str = jfmt.str, len = jfmt.len, ch = jfmt["char"]; let str = jfmt.str, len = jfmt.len, ch = jfmt["char"];
switch (ch) { switch (ch) {
case "E": // 星期 case "E": // 星期
str = getFullDayName(date.getDay()); str = getFullDayName(date.getDay());
@ -823,7 +826,7 @@ export const date2Str = function (date, format) {
} }
break; break;
case "h": // 时(12) case "h": // 时(12)
var hour = date.getHours() % 12; let hour = date.getHours() % 12;
if (hour === 0) { if (hour === 0) {
hour = 12; hour = 12;
} }
@ -875,7 +878,7 @@ export const object2Number = function (value) {
if (typeof value === "number") { if (typeof value === "number") {
return value; return value;
} }
var str = value + ""; const str = value + "";
if (str.indexOf(".") === -1) { if (str.indexOf(".") === -1) {
return parseInt(str); return parseInt(str);
} }
@ -891,9 +894,9 @@ export const object2Date = function (obj) {
} else if (typeof obj === "number") { } else if (typeof obj === "number") {
return new Date(obj); return new Date(obj);
} }
var str = obj + ""; let str = obj + "";
str = str.replace(/-/g, "/"); str = str.replace(/-/g, "/");
var dt = new Date(str); const dt = new Date(str);
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return dt; return dt;
} }
@ -909,9 +912,9 @@ export const object2Time = function (obj) {
if (obj instanceof Date) { if (obj instanceof Date) {
return obj; return obj;
} }
var str = obj + ""; let str = obj + "";
str = str.replace(/-/g, "/"); str = str.replace(/-/g, "/");
var dt = new Date(str); let dt = new Date(str);
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return dt; return dt;
} }

84
src/core/func/date.js

@ -48,7 +48,7 @@ export function getTimezone(date) {
* Returns the number of days in the current month * Returns the number of days in the current month
*/ */
export function getMonthDays(date, month = date.getMonth()) { export function getMonthDays(date, month = date.getMonth()) {
var year = date.getFullYear(); const year = date.getFullYear();
if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) { if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) {
return 29; return 29;
} }
@ -77,9 +77,9 @@ export function getLastDateOfMonth(date) {
* @returns {number} * @returns {number}
*/ */
export function getDayOfYear(date) { export function getDayOfYear(date) {
var now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); const now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var then = getDate(date.getFullYear(), 0, 0, 0, 0, 0); const then = getDate(date.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then; const time = now - then;
return Math.floor(time / DAY); return Math.floor(time / DAY);
} }
@ -90,16 +90,16 @@ export function getDayOfYear(date) {
* @returns {number} * @returns {number}
*/ */
export function getWeekNumber(date) { export function getWeekNumber(date) {
var d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); const d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var week = d.getDay(); const week = d.getDay();
var startOfWeek = BI.StartOfWeek % 7; const startOfWeek = BI.StartOfWeek % 7;
var middleDay = (startOfWeek + 3) % 7; let middleDay = (startOfWeek + 3) % 7;
middleDay = middleDay || 7; middleDay = middleDay || 7;
// 偏移到周周首之前需要多少天 // 偏移到周周首之前需要多少天
var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); const offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek);
var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); const offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek);
d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount);
var ms = d.valueOf(); const ms = d.valueOf();
d.setMonth(0); d.setMonth(0);
d.setDate(1); d.setDate(1);
return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1;
@ -120,9 +120,9 @@ export function getOffsetDate(date, offset) {
} }
export function getOffsetQuarter(date, n) { export function getOffsetQuarter(date, n) {
var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
var day = dt.getDate(); let day = dt.getDate();
var monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1)); const monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1));
if (day > monthDay) { if (day > monthDay) {
day = monthDay; day = monthDay;
} }
@ -137,8 +137,8 @@ export function getOffsetQuarter(date, n) {
* @returns {number} * @returns {number}
*/ */
export function getQuarterStartMonth(date) { export function getQuarterStartMonth(date) {
var quarterStartMonth = 0; let quarterStartMonth = 0;
var nowMonth = date.getMonth(); const nowMonth = date.getMonth();
if (nowMonth < 3) { if (nowMonth < 3) {
quarterStartMonth = 0; quarterStartMonth = 0;
} }
@ -169,7 +169,7 @@ export function getQuarterStartDate(date) {
* @returns {Date} * @returns {Date}
*/ */
export function getQuarterEndDate(date) { export function getQuarterEndDate(date) {
var quarterEndMonth = getQuarterStartMonth(date) + 2; const quarterEndMonth = getQuarterStartMonth(date) + 2;
return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date)); return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date));
} }
@ -180,9 +180,9 @@ export function getQuarterEndDate(date) {
* @returns {Date} * @returns {Date}
*/ */
export function getOffsetMonth(date, n) { export function getOffsetMonth(date, n) {
var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
var day = dt.getDate(); let day = dt.getDate();
var monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1)); const monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1));
if (day > monthDay) { if (day > monthDay) {
day = monthDay; day = monthDay;
} }
@ -197,8 +197,8 @@ export function getOffsetMonth(date, n) {
* @returns {Date} * @returns {Date}
*/ */
export function getWeekStartDate(date) { export function getWeekStartDate(date) {
var w = date.getDay(); const w = date.getDay();
var startOfWeek = BI.StartOfWeek % 7; const startOfWeek = BI.StartOfWeek % 7;
return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]);
} }
@ -208,8 +208,8 @@ export function getWeekStartDate(date) {
* @returns {Date} * @returns {Date}
*/ */
export function getWeekEndDate(date) { export function getWeekEndDate(date) {
var w = date.getDay(); const w = date.getDay();
var startOfWeek = BI.StartOfWeek % 7; const startOfWeek = BI.StartOfWeek % 7;
return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6); return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6);
} }
@ -273,26 +273,26 @@ export function getQuarterName(index) {
* @returns {*} * @returns {*}
*/ */
export function print(date, str) { export function print(date, str) {
var m = date.getMonth(); const m = date.getMonth();
var d = date.getDate(); const d = date.getDate();
var y = date.getFullYear(); const y = date.getFullYear();
var yWith4number = y + ""; let yWith4number = y + "";
while (yWith4number.length < 4) { while (yWith4number.length < 4) {
yWith4number = "0" + yWith4number; yWith4number = "0" + yWith4number;
} }
var wn = getWeekNumber(date); const wn = getWeekNumber(date);
var qr = getQuarter(date); const qr = getQuarter(date);
var w = date.getDay(); const w = date.getDay();
var s = {}; const s = {};
var hr = date.getHours(); const hr = date.getHours();
var pm = (hr >= 12); const pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr; let ir = (pm) ? (hr - 12) : hr;
var dy = getDayOfYear(date); const dy = getDayOfYear(date);
if (ir === 0) { if (ir === 0) {
ir = 12; ir = 12;
} }
var min = date.getMinutes(); const min = date.getMinutes();
var sec = date.getSeconds(); const sec = date.getSeconds();
s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N] s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N]
s["%A"] = getFullDayName(w); // full weekday name s["%A"] = getFullDayName(w); // full weekday name
s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N] s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N]
@ -331,7 +331,7 @@ export function print(date, str) {
s["%q"] = "0" + qr; s["%q"] = "0" + qr;
s["%Q"] = qr; s["%Q"] = qr;
var re = /%./g; let re = /%./g;
BI.isKhtml = BI.isKhtml || function () { BI.isKhtml = BI.isKhtml || function () {
if (!_global.navigator) { if (!_global.navigator) {
return false; return false;
@ -366,9 +366,9 @@ export function print(date, str) {
return s[par] || par; return s[par] || par;
}); });
} }
var a = str.match(re); const a = str.match(re);
for (var i = 0; i < a.length; i++) { for (let i = 0; i < a.length; i++) {
var tmp = s[a[i]]; const tmp = s[a[i]];
if (tmp) { if (tmp) {
re = new RegExp(a[i], "g"); re = new RegExp(a[i], "g");
str = str.replace(re, tmp); str = str.replace(re, tmp);

36
src/core/func/function.js

@ -12,7 +12,7 @@ import {makeFirstPY} from "../utils/chinesePY";
* @returns {*} * @returns {*}
*/ */
export function createDistinctName(array, name) { export function createDistinctName(array, name) {
var src = name, idx = 1; let src = name, idx = 1;
name = name || ""; name = name || "";
while (true) { while (true) {
if (every(array, function (i, item) { if (every(array, function (i, item) {
@ -43,18 +43,18 @@ export function getGBWidth(str) {
* @param param 搜索哪个属性 * @param param 搜索哪个属性
*/ */
export function getSearchResult(items, keyword, param) { export function getSearchResult(items, keyword, param) {
var array = isArray(items); let array = isArray(items);
items = array ? BI.flatten(items) : items; items = array ? BI.flatten(items) : items;
param || (param = "text"); param || (param = "text");
if (!isKey(keyword)) { if (!isKey(keyword)) {
return { return {
find: items, find: items,
match: array ? [] : {} match: array ? [] : {},
}; };
} }
var t, text, py; let t, text, py;
keyword = toUpperCase(keyword); keyword = toUpperCase(keyword);
var matched = array ? [] : {}, find = array ? [] : {}; let matched = array ? [] : {}, find = array ? [] : {};
each(items, function (i, item) { each(items, function (i, item) {
// 兼容item为null的处理 // 兼容item为null的处理
if (isNull(item)) { if (isNull(item)) {
@ -66,11 +66,11 @@ export function getSearchResult(items, keyword, param) {
if (isNull(text) || isObject(text)) return; if (isNull(text) || isObject(text)) return;
py = makeFirstPY(text, { py = makeFirstPY(text, {
splitChar: "\u200b" splitChar: "\u200b",
}); });
text = toUpperCase(text); text = toUpperCase(text);
py = toUpperCase(py); py = toUpperCase(py);
var pidx; let pidx;
if (text.indexOf(keyword) > -1) { if (text.indexOf(keyword) > -1) {
if (text === keyword) { if (text === keyword) {
array ? matched.push(item) : (matched[i] = item); array ? matched.push(item) : (matched[i] = item);
@ -90,7 +90,7 @@ export function getSearchResult(items, keyword, param) {
}); });
return { return {
match: matched, match: matched,
find: find find: find,
}; };
} }
@ -101,7 +101,7 @@ export function getSearchResult(items, keyword, param) {
* @return {any[]} * @return {any[]}
*/ */
export function getSortedResult(items, key) { export function getSortedResult(items, key) {
var getTextOfItem = BI.isFunction(key) ? key : let getTextOfItem = BI.isFunction(key) ? key :
function (item, key) { function (item, key) {
if (BI.isNotNull(key)) { if (BI.isNotNull(key)) {
return item[key]; return item[key];
@ -116,8 +116,8 @@ export function getSortedResult(items, key) {
}; };
return items.sort(function (item1, item2) { return items.sort(function (item1, item2) {
var str1 = getTextOfItem(item1, key); let str1 = getTextOfItem(item1, key);
var str2 = getTextOfItem(item2, key); let str2 = getTextOfItem(item2, key);
if (BI.isNull(str1) && BI.isNull(str2)) { if (BI.isNull(str1) && BI.isNull(str2)) {
return 0; return 0;
} }
@ -130,10 +130,10 @@ export function getSortedResult(items, key) {
if (str1 === str2) { if (str1 === str2) {
return 0; return 0;
} }
var len1 = str1.length, len2 = str2.length; let len1 = str1.length, len2 = str2.length;
for (var i = 0; i < len1 && i < len2; i++) { for (let i = 0; i < len1 && i < len2; i++) {
var char1 = str1[i]; let char1 = str1[i];
var char2 = str2[i]; let char2 = str2[i];
if (char1 !== char2) { if (char1 !== char2) {
// 找不到的字符都往后面放 // 找不到的字符都往后面放
return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]);
@ -144,7 +144,7 @@ export function getSortedResult(items, key) {
} }
export function beforeFunc(sFunc, func) { export function beforeFunc(sFunc, func) {
var __self = sFunc; let __self = sFunc;
return function () { return function () {
if (func.apply(sFunc, arguments) === false) { if (func.apply(sFunc, arguments) === false) {
return false; return false;
@ -154,9 +154,9 @@ export function beforeFunc(sFunc, func) {
} }
export function afterFunc(sFunc, func) { export function afterFunc(sFunc, func) {
var __self = sFunc; let __self = sFunc;
return function () { return function () {
var ret = __self.apply(sFunc, arguments); let ret = __self.apply(sFunc, arguments);
if (ret === false) { if (ret === false) {
return false; return false;
} }

34
src/core/func/number.js

@ -9,7 +9,7 @@ export function add(num, arg) {
** 返回值arg1加上arg2的精确结果 ** 返回值arg1加上arg2的精确结果
**/ **/
function accAdd(arg1, arg2) { function accAdd(arg1, arg2) {
var r1, r2, m, c; let r1, r2, m, c;
try { try {
r1 = arg1.toString().split(".")[1].length; r1 = arg1.toString().split(".")[1].length;
} catch (e) { } catch (e) {
@ -23,7 +23,7 @@ export function add(num, arg) {
c = Math.abs(r1 - r2); c = Math.abs(r1 - r2);
m = Math.pow(10, Math.max(r1, r2)); m = Math.pow(10, Math.max(r1, r2));
if (c > 0) { if (c > 0) {
var cm = Math.pow(10, c); let cm = Math.pow(10, c);
if (r1 > r2) { if (r1 > r2) {
arg1 = Number(arg1.toString().replace(".", "")); arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm; arg2 = Number(arg2.toString().replace(".", "")) * cm;
@ -50,7 +50,7 @@ export function sub(num, arg) {
** 返回值arg1加上arg2的精确结果 ** 返回值arg1加上arg2的精确结果
**/ **/
function accSub(arg1, arg2) { function accSub(arg1, arg2) {
var r1, r2, m, n; let r1, r2, m, n;
try { try {
r1 = arg1.toString().split(".")[1].length; r1 = arg1.toString().split(".")[1].length;
} catch (e) { } catch (e) {
@ -78,7 +78,7 @@ export function mul(num, arg) {
** 返回值arg1乘以 arg2的精确结果 ** 返回值arg1乘以 arg2的精确结果
**/ **/
function accMul(arg1, arg2) { function accMul(arg1, arg2) {
var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
try { try {
m += s1.split(".")[1].length; m += s1.split(".")[1].length;
} catch (e) { } catch (e) {
@ -101,8 +101,8 @@ export function div(num, arg) {
*/ */
function digitLength(num) { function digitLength(num) {
// Get digit length of e // Get digit length of e
var eSplit = num.toString().split(/[eE]/); let eSplit = num.toString().split(/[eE]/);
var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); let len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0));
return len > 0 ? len : 0; return len > 0 ? len : 0;
} }
@ -114,7 +114,7 @@ export function div(num, arg) {
if (num.toString().indexOf("e") === -1) { if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", "")); return Number(num.toString().replace(".", ""));
} }
var dLen = digitLength(num); let dLen = digitLength(num);
return dLen > 0 ? num * Math.pow(10, dLen) : num; return dLen > 0 ? num * Math.pow(10, dLen) : num;
} }
@ -122,17 +122,17 @@ export function div(num, arg) {
* 精确乘法 * 精确乘法
*/ */
function times(num1, num2) { function times(num1, num2) {
var others = []; let others = [];
for (var _i = 2; _i < arguments.length; _i++) { for (let _i = 2; _i < arguments.length; _i++) {
others[_i - 2] = arguments[_i]; others[_i - 2] = arguments[_i];
} }
if (others.length > 0) { if (others.length > 0) {
return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1)));
} }
var num1Changed = float2Fixed(num1); let num1Changed = float2Fixed(num1);
var num2Changed = float2Fixed(num2); let num2Changed = float2Fixed(num2);
var baseNum = digitLength(num1) + digitLength(num2); let baseNum = digitLength(num1) + digitLength(num2);
var leftValue = num1Changed * num2Changed; let leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum); return leftValue / Math.pow(10, baseNum);
} }
@ -140,15 +140,15 @@ export function div(num, arg) {
* 精确除法 * 精确除法
*/ */
function accDivide(num1, num2) { function accDivide(num1, num2) {
var others = []; let others = [];
for (var _i = 2; _i < arguments.length; _i++) { for (let _i = 2; _i < arguments.length; _i++) {
others[_i - 2] = arguments[_i]; others[_i - 2] = arguments[_i];
} }
if (others.length > 0) { if (others.length > 0) {
return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1)));
} }
var num1Changed = float2Fixed(num1); let num1Changed = float2Fixed(num1);
var num2Changed = float2Fixed(num2); let num2Changed = float2Fixed(num2);
return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1))); return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
} }
} }

14
src/core/func/string.js

@ -11,7 +11,7 @@ export function startWith(str, startTag) {
if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) {
return false; return false;
} }
return str.substr(0, startTag.length) == startTag; return str.substring(0, startTag.length) == startTag;
} }
/** /**
@ -34,8 +34,8 @@ export function endWith(str, endTag) {
* @return {String} 参数的值 * @return {String} 参数的值
*/ */
export function getQuery(str, name) { export function getQuery(str, name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = str.substr(str.indexOf("?") + 1).match(reg); let r = str.substr(str.indexOf("?") + 1).match(reg);
if (r) { if (r) {
return unescape(r[2]); return unescape(r[2]);
} }
@ -52,7 +52,7 @@ export function appendQuery(str, paras) {
if (!paras) { if (!paras) {
return str; return str;
} }
var src = str; let src = str;
// 没有问号说明还没有参数 // 没有问号说明还没有参数
if (src.indexOf("?") === -1) { if (src.indexOf("?") === -1) {
src += "?"; src += "?";
@ -106,10 +106,10 @@ export function allIndexOf(str, sub) {
if (typeof sub !== "string") { if (typeof sub !== "string") {
return []; return [];
} }
var location = []; let location = [];
var offset = 0; let offset = 0;
while (str.length > 0) { while (str.length > 0) {
var loc = str.indexOf(sub); let loc = str.indexOf(sub);
if (loc === -1) { if (loc === -1) {
break; break;
} }

Loading…
Cancel
Save