Browse Source

Pull request #3301: KERNEL-13991 feat: core/func文件夹

Merge in VISUAL/fineui from ~DAILER/fineui:es6 to es6

* commit '3955ff070b17a9c8eb1b7020bd8adf0bdffac767':
  KERNEL-13991 feat: core/func文件夹
  KERNEL-13991 feat: core/func文件夹
  KERNEL-13991 feat: core/func文件夹
es6
Dailer-刘荣歆 2 years ago
parent
commit
b4d01e95aa
  1. 24
      src/core/2.base.js
  2. 4
      src/core/func/__test__/function.test.js
  3. 439
      src/core/func/alias.js
  4. 25
      src/core/func/array.js
  5. 347
      src/core/func/date.js
  6. 126
      src/core/func/function.js
  7. 23
      src/core/func/index.js
  8. 76
      src/core/func/number.js
  9. 70
      src/core/func/string.js
  10. 14
      src/core/index.js
  11. 59
      src/core/platform/web/detectElementResize.js
  12. 39
      src/core/utils/chinesePY.js

24
src/core/2.base.js

@ -157,8 +157,10 @@ BI._.extend(BI, {
BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) {
BI[name] = _apply(name); BI[name] = _apply(name);
}); });
BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", BI._.each([
"sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { "get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min",
"sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"
], function (name) {
if (name === "any") { if (name === "any") {
BI[name] = _applyFunc("some"); BI[name] = _applyFunc("some");
} else { } else {
@ -404,8 +406,10 @@ BI._.extend(BI, {
}); });
// 数组相关的方法 // 数组相关的方法
BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", BI._.each([
"difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection",
"difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"
], function (name) {
BI[name] = _apply(name); BI[name] = _apply(name);
}); });
BI._.each(["findIndex", "findLastIndex"], function (name) { BI._.each(["findIndex", "findLastIndex"], function (name) {
@ -497,10 +501,12 @@ BI._.extend(BI, {
}); });
// 对象相关方法 // 对象相关方法
BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", BI._.each([
"keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn",
"defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty",
"isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite",
"isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"
], function (name) {
BI[name] = _apply(name); BI[name] = _apply(name);
}); });
export const keys = BI.keys; export const keys = BI.keys;
@ -666,6 +672,7 @@ BI._.extend(BI, {
export const deepClone = BI._.cloneDeep; export const deepClone = BI._.cloneDeep;
export const deepExtend = BI._.deepExtend; export const deepExtend = BI._.deepExtend;
export function isDeepMatch(object, attrs) { export function isDeepMatch(object, attrs) {
let attrsKeys = keys(attrs), length = attrsKeys.length; let attrsKeys = keys(attrs), length = attrsKeys.length;
if (object == null) { if (object == null) {
@ -1351,9 +1358,8 @@ export function parseDateTime(str, fmt) {
return today; return today;
} }
export function getDate() { export function getDate(...args) {
const length = arguments.length; const length = args.length;
const args = arguments;
let dt; let dt;
switch (length) { switch (length) {
// new Date() // new Date()

4
src/core/func/__test__/function.test.js

@ -8,7 +8,7 @@ describe("core-function-test", function () {
* test_author_lei.wang * test_author_lei.wang
*/ */
it("createDistinctName-支持字符串数组", function () { it("createDistinctName-支持字符串数组", function () {
var names = ["name", "name1"]; const names = ["name", "name1"];
expect(BI.Func.createDistinctName(names, "name")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name")).to.equal("name2");
expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2");
}); });
@ -17,7 +17,7 @@ describe("core-function-test", function () {
* test_author_lei.wang * test_author_lei.wang
*/ */
it("createDistinctName-支持对象数组数组", function () { it("createDistinctName-支持对象数组数组", function () {
var names = [{ name: "name" }, { name: "name1" }]; const names = [{ name: "name" }, { name: "name1" }];
expect(BI.Func.createDistinctName(names, "name")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name")).to.equal("name2");
expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2");
}); });

439
src/core/func/alias.js

@ -1,35 +1,37 @@
(function () { import {each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseDateTime, values} from "../2.base";
var _global; import {replaceAll} from "./string";
if (typeof window !== "undefined") { import {getFullDayName, getMonthName, getTimezone} from "./date";
let _global;
if (typeof window !== "undefined") {
_global = window; _global = window;
} else if (typeof global !== "undefined") { } else if (typeof global !== "undefined") {
_global = global; _global = global;
} else if (typeof self !== "undefined") { } else if (typeof self !== "undefined") {
_global = self; _global = self;
} else { } else {
_global = this; _global = this;
} }
if (!_global.BI) { if (!_global.BI) {
_global.BI = {}; _global.BI = {};
} }
function isEmpty (value) { function isEmpty(value) {
// 判断是否为空值 // 判断是否为空值
var result = value === "" || value === null || value === undefined; return value === "" || value === null || value === undefined;
return result; }
}
// 判断是否是无效的日期 // 判断是否是无效的日期
function isInvalidDate (date) { function isInvalidDate(date) {
return date == "Invalid Date" || date == "NaN"; return date === "Invalid Date" || date === "NaN";
} }
/** /**
* CHART-1400 * CHART-1400
* 使用数值计算的方式来获取任意数值的科学技术表示值 * 使用数值计算的方式来获取任意数值的科学技术表示值
* 科学计数格式 * 科学计数格式
*/ */
function _eFormat (text, fmt) { function _eFormat(text, fmt) {
text = +text; text = +text;
return eFormat(text, fmt); return eFormat(text, fmt);
@ -44,13 +46,13 @@
* 数量级没有规定因为没见过实数里有用科学计数法表示之后E的后面会小于一位的情况0无所谓 * 数量级没有规定因为没见过实数里有用科学计数法表示之后E的后面会小于一位的情况0无所谓
* @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");
@ -65,15 +67,15 @@
} }
// 计算出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);
@ -90,7 +92,7 @@
} }
// 获取format格式规定的数量级的形式 // 获取format格式规定的数量级的形式
function formatExponential (format, num, magnitudeNeg) { function formatExponential(format, num, magnitudeNeg) {
num += ""; num += "";
if (!/e/ig.test(format)) { if (!/e/ig.test(format)) {
return num; return num;
@ -102,8 +104,8 @@
} }
// 如果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;
} }
@ -115,25 +117,25 @@
} }
// 获取format规定的科学计数法精确到的位数 // 获取format规定的科学计数法精确到的位数
function getPrecision (format) { function getPrecision(format) {
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;
} }
// 获取数值科学计数法表示之后整数的位数 // 获取数值科学计数法表示之后整数的位数
// 这边我们还需要考虑#和0的问题 // 这边我们还需要考虑#和0的问题
function getInteger (magnitude, format) { function getInteger(magnitude, format) {
if (!/e/ig.test(format)) { if (!/e/ig.test(format)) {
return 0; return 0;
} }
// 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);
@ -147,24 +149,24 @@
} }
// 判断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;
} }
} }
//'#.##'之类的格式处理 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++;
} }
@ -173,13 +175,13 @@
} }
return text; return text;
} }
/** /**
* 数字格式 * 数字格式
*/ */
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) {
@ -187,12 +189,12 @@
} }
// 数字格式,区分正负数 // 数字格式,区分正负数
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));
} }
return _numberFormat((-text) + "", format.substr(numMod + 1)); return _numberFormat((-text) + "", format.substring(numMod + 1));
} else { } else {
// 兼容格式处理负数的情况(copy:fr-jquery.format.js) // 兼容格式处理负数的情况(copy:fr-jquery.format.js)
@ -201,19 +203,19 @@
} }
} }
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"; const paddingZero = /[%]$/.test(format) ? "00" : "000";
tright += paddingZero; tright += paddingZero;
tleft += tright.substr(0, paddingZero.length); tleft += tright.substring(0, paddingZero.length);
tleft = tleft.replace(/^0+/gi, ""); tleft = tleft.replace(/^0+/gi, "");
tright = tright.substr(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 + "";
@ -221,7 +223,7 @@
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";
} }
@ -230,20 +232,20 @@
} else { } else {
return left + "." + right; return left + "." + right;
} }
} }
/** /**
* 处理小数点右边小数部分 * 处理小数点右边小数部分
* @param tright 右边内容 * @param tright 右边内容
* @param fright 右边格式 * @param fright 右边格式
* @returns {JSON} 返回处理结果和整数部分是否需要进位 * @returns {JSON} 返回处理结果和整数部分是否需要进位
* @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)) {
@ -261,21 +263,21 @@
break; break;
} }
} }
var rll = tright.substr(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.substr(1); newnum = newnum.substring(1);
} else { } else {
newnum = BI.leftPad(newnum, orilen, "0"); newnum = leftPad(newnum, orilen, "0");
result.leftPlus = false; result.leftPlus = false;
} }
right = right.replace(/^[0-9]+/, newnum); right = right.replace(/^[0-9]+/, newnum);
@ -283,23 +285,24 @@
} }
result.num = right; result.num = right;
return result; return result;
} }
/** /**
* 处理小数点左边整数部分 * 处理小数点左边整数部分
* @param tleft 左边内容 * @param tleft 左边内容
* @param fleft 左边格式 * @param fleft 左边格式
* @returns {string} 返回处理结果 * @returns {string} 返回处理结果
* @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)) {
@ -317,7 +320,7 @@
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;
} }
@ -331,19 +334,20 @@
} }
if (last > -1) { if (last > -1) {
// 处理剩余字符 // 处理剩余字符
var tll = tleft.substr(0, j + 1); const tll = tleft.substring(0, j + 1);
left = left.substr(0, last) + tll + left.substr(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.substr(n, combo) + "," + newstr; newstr = res.substring(n, combo) + "," + newstr;
} }
var lres = res.substr(0, n + combo); const lres = res.substring(0, n + combo);
if (!isEmpty(lres)) { if (!isEmpty(lres)) {
newstr = lres + "," + newstr; newstr = lres + "," + newstr;
} }
@ -351,18 +355,17 @@
left = left.replace(/[0-9]+,/, newstr); left = left.replace(/[0-9]+,/, newstr);
} }
return left; return left;
} }
BI.cjkEncode = function (text) { export const cjkEncode = function (text) {
// alex:如果非字符串,返回其本身(cjkEncode(234) 返回 ""是不对的) // alex:如果非字符串,返回其本身(cjkEncode(234) 返回 ""是不对的)
if (typeof text !== "string") { if (typeof text !== "string") {
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 {
@ -371,31 +374,31 @@
} }
return newText; return newText;
}; };
/** /**
* 将cjkEncode处理过的字符串转化为原始字符串 * 将cjkEncode处理过的字符串转化为原始字符串
* *
* @static * @static
* @param text 需要做解码的字符串 * @param text 需要做解码的字符串
* @return {String} 解码后的字符串 * @return {String} 解码后的字符串
*/ */
BI.cjkDecode = function (text) { export const cjkDecode = function (text) {
if (text == null) { if (text == null) {
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); const 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));
@ -409,25 +412,25 @@
} }
return newText; return newText;
}; };
// replace the html special tags // replace the html special tags
var SPECIAL_TAGS = { const SPECIAL_TAGS = {
"&": "&amp;", "&": "&amp;",
"\"": "&quot;", "\"": "&quot;",
"<": "&lt;", "<": "&lt;",
">": "&gt;", ">": "&gt;",
"\x20": "&nbsp;", "\x20": "&nbsp;",
"\n": "&#10;" "\n": "&#10;",
}; };
BI.htmlEncode = function (text) { export const htmlEncode = function (text) {
return BI.isNull(text) ? "" : BI.replaceAll(text + "", BI.keys(SPECIAL_TAGS).join("|"), function (v) { return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) {
return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v; return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v;
}); });
}; };
// html decode // html decode
BI.htmlDecode = function (text) { export const htmlDecode = function (text) {
return BI.isNull(text) ? "" : BI.replaceAll(text + "", BI.values(SPECIAL_TAGS).join("|"), function (v) { return isNull(text) ? "" : replaceAll(text + "", values(SPECIAL_TAGS).join("|"), function (v) {
switch (v) { switch (v) {
case "&amp;": case "&amp;":
return "&"; return "&";
@ -445,45 +448,45 @@
return v; return v;
} }
}); });
}; };
BI.cjkEncodeDO = function (o) { export const cjkEncodeDO = function (o) {
if (BI.isPlainObject(o)) { if (isPlainObject(o)) {
var result = {}; const result = {};
BI._.each(o, function (v, k) { each(o, function (v, k) {
if (!(typeof v === "string")) { if (!(typeof v === "string")) {
v = BI.jsonEncode(v); v = jsonEncode(v);
} }
// wei:bug 43338,如果key是中文,cjkencode后o的长度就加了1,ie9以下版本死循环,所以新建对象result。 // wei:bug 43338,如果key是中文,cjkencode后o的长度就加了1,ie9以下版本死循环,所以新建对象result。
k = BI.cjkEncode(k); k = cjkEncode(k);
result[k] = BI.cjkEncode(v); result[k] = cjkEncode(v);
}); });
return result; return result;
} }
return o; return o;
}; };
BI.jsonEncode = function (o) { export const jsonEncode = function (o) {
// james:这个Encode是抄的EXT的 // james:这个Encode是抄的EXT的
var useHasOwn = !!{}.hasOwnProperty; const 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 = { const 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) { const 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;
} }
@ -496,8 +499,8 @@
return "\"" + s + "\""; return "\"" + s + "\"";
}; };
var encodeArray = function (o) { const 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) {
@ -509,7 +512,7 @@
if (b) { if (b) {
a.push(","); a.push(",");
} }
a.push(v === null ? "null" : BI.jsonEncode(v)); a.push(v === null ? "null" : jsonEncode(v));
b = true; b = true;
} }
} }
@ -519,15 +522,15 @@
if (typeof o === "undefined" || o === null) { if (typeof o === "undefined" || o === null) {
return "null"; return "null";
} else if (BI.isArray(o)) { } else if (isArray(o)) {
return encodeArray(o); return encodeArray(o);
} else if (o instanceof Date) { } else if (o instanceof Date) {
/* /*
* alex:原来只是把年月日时分秒简单地拼成一个String,无法decode * alex:原来只是把年月日时分秒简单地拼成一个String,无法decode
* 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下 * 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下
*/ */
return BI.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);
@ -535,10 +538,10 @@
return isFinite(o) ? String(o) : "null"; return isFinite(o) ? String(o) : "null";
} else if (typeof o === "boolean") { } else if (typeof o === "boolean") {
return String(o); return String(o);
} else if (BI.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];
@ -550,8 +553,8 @@
if (b) { if (b) {
a.push(","); a.push(",");
} }
a.push(BI.jsonEncode(i), ":", a.push(jsonEncode(i), ":",
v === null ? "null" : BI.jsonEncode(v)); v === null ? "null" : jsonEncode(v));
b = true; b = true;
} }
} }
@ -559,14 +562,13 @@
a.push("}"); a.push("}");
return a.join(""); return a.join("");
}; };
BI.jsonDecode = function (text) { export const jsonDecode = function (text) {
let jo;
try { try {
// 注意0啊 jo = JSON.parse(text);
// var jo = $.parseJSON(text) || {};
var jo = BI.$ ? BI.$.parseJSON(text) : _global.JSON.parse(text);
if (jo == null) { if (jo == null) {
jo = {}; jo = {};
} }
@ -588,32 +590,32 @@
return jo; return jo;
} }
function _hasDateInJson (json) { function _hasDateInJson(json) {
if (!json || typeof json !== "string") { if (!json || typeof json !== "string") {
return false; return false;
} }
return json.indexOf("__time__") != -1; return json.indexOf("__time__") !== -1;
} }
return (function (o) { return (function parse(o) {
if (typeof o === "string") { if (typeof o === "string") {
return o; return o;
} }
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" || BI._.isFunction(o[a])) { if (o[a] === o || typeof o[a] === "object" || isFunction(o[a])) {
break; break;
} }
o[a] = arguments.callee(o[a]); o[a] = parse(o[a]);
} }
return o; return o;
})(jo); })(jo);
}; };
/** /**
* 获取编码后的url * 获取编码后的url
* @param urlTemplate url模板 * @param urlTemplate url模板
* @param param 参数 * @param param 参数
@ -621,16 +623,16 @@
* @example * @example
* BI.getEncodeURL("design/{tableName}/{fieldName}",{tableName: "A", fieldName: "a"}) // design/A/a * BI.getEncodeURL("design/{tableName}/{fieldName}",{tableName: "A", fieldName: "a"}) // design/A/a
*/ */
BI.getEncodeURL = function (urlTemplate, param) { export const getEncodeURL = function (urlTemplate, param) {
return BI.replaceAll(urlTemplate, "\\{(.*?)\\}", function (ori, str) { return replaceAll(urlTemplate, "\\{(.*?)\\}", function (ori, str) {
return BI.encodeURIComponent(BI.isObject(param) ? param[str] : param); return encodeURIComponent(isObject(param) ? param[str] : param);
}); });
}; };
BI.encodeURIComponent = function (url) { export const encodeURIComponent = function (url) {
BI.specialCharsMap = BI.specialCharsMap || {}; BI.specialCharsMap = BI.specialCharsMap || {};
url = url || ""; url = url || "";
url = BI.replaceAll(url + "", BI.keys(BI.specialCharsMap || []).join("|"), function (str) { url = replaceAll(url + "", keys(BI.specialCharsMap || []).join("|"), function (str) {
switch (str) { switch (str) {
case "\\": case "\\":
return BI.specialCharsMap["\\\\"] || str; return BI.specialCharsMap["\\\\"] || str;
@ -639,26 +641,26 @@
} }
}); });
return _global.encodeURIComponent(url); return _global.encodeURIComponent(url);
}; };
BI.decodeURIComponent = function (url) { export const decodeURIComponent = function (url) {
var reserveSpecialCharsMap = {}; const reserveSpecialCharsMap = {};
BI.each(BI.specialCharsMap, function (initialChar, encodeChar) { each(BI.specialCharsMap, function (initialChar, encodeChar) {
reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar;
}); });
url = url || ""; url = url || "";
url = BI.replaceAll(url + "", BI.keys(reserveSpecialCharsMap || []).join("|"), function (str) { url = replaceAll(url + "", keys(reserveSpecialCharsMap || []).join("|"), function (str) {
return reserveSpecialCharsMap[str] || str; return reserveSpecialCharsMap[str] || str;
}); });
return _global.decodeURIComponent(url); return _global.decodeURIComponent(url);
}; };
BI.contentFormat = function (cv, fmt) { export const contentFormat = function (cv, fmt) {
if (isEmpty(cv)) { if (isEmpty(cv)) {
// 原值为空,返回空字符 // 原值为空,返回空字符
return ""; return "";
} }
var text = cv.toString(); let text = cv.toString();
if (isEmpty(fmt)) { if (isEmpty(fmt)) {
// 格式为空,返回原字符 // 格式为空,返回原字符
return text; return text;
@ -677,9 +679,9 @@
cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/"))); cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/")));
} }
} }
if (!isInvalidDate(cv) && !BI.isNull(cv)) { if (!isInvalidDate(cv) && !isNull(cv)) {
var needTrim = fmt.match(/^DT/); const needTrim = fmt.match(/^DT/);
text = BI.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/)) {
// 科学计数格式 // 科学计数格式
@ -691,15 +693,14 @@
// ¤ - 货币格式 // ¤ - 货币格式
text = text.replace(/¤/g, "¥"); text = text.replace(/¤/g, "¥");
return text; return text;
}; };
/** /**
* 将Java提供的日期格式字符串装换为JS识别的日期格式字符串 * 将Java提供的日期格式字符串装换为JS识别的日期格式字符串
* @class FR.parseFmt
* @param fmt 日期格式 * @param fmt 日期格式
* @returns {String} * @returns {string}
*/ */
BI.parseFmt = function (fmt) { export const parseFmt = function (fmt) {
if (!fmt) { if (!fmt) {
return ""; return "";
} }
@ -736,54 +737,49 @@
.replace(/s{2,}/g, "%S"); .replace(/s{2,}/g, "%S");
return fmt; return fmt;
}; };
/** /**
* 把字符串按照对应的格式转化成日期对象 * 把字符串按照对应的格式转化成日期对象
* *
* @example * @example
* var result = BI.str2Date('2013-12-12', 'yyyy-MM-dd');//Thu Dec 12 2013 00:00:00 GMT+0800 * var result = BI.str2Date('2013-12-12', 'yyyy-MM-dd');//Thu Dec 12 2013 00:00:00 GMT+0800
*
* @class BI.str2Date
* @param str 字符串 * @param str 字符串
* @param format 日期格式 * @param format 日期格式
* @returns {*} * @returns {Date}
*/ */
BI.str2Date = function (str, format) { 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 = BI.parseFmt(format); const fmt = parseFmt(format);
return BI.parseDateTime(str, fmt); return parseDateTime(str, fmt);
}; };
/** /**
* 把日期对象按照指定格式转化成字符串 * 把日期对象按照指定格式转化成字符串
* *@example
* @example
* var date = new Date('Thu Dec 12 2013 00:00:00 GMT+0800'); * var date = new Date('Thu Dec 12 2013 00:00:00 GMT+0800');
* var result = BI.date2Str(date, 'yyyy-MM-dd');//2013-12-12 * var result = BI.date2Str(date, 'yyyy-MM-dd');//2013-12-12
* * @param date
* @class BI.date2Str * @param format
* @param date 日期 * @returns {string}
* @param format 日期格式
* @returns {String}
*/ */
BI.date2Str = function (date, format) { export const date2Str = function (date, format) {
if (!date) { if (!date) {
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;
@ -795,16 +791,16 @@
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 = BI.getFullDayName(date.getDay()); str = getFullDayName(date.getDay());
break; break;
case "y": // 年 case "y": // 年
if (len <= 3) { if (len <= 3) {
@ -815,48 +811,48 @@
break; break;
case "M": // 月 case "M": // 月
if (len > 2) { if (len > 2) {
str = BI.getMonthName(date.getMonth()); str = getMonthName(date.getMonth());
} else if (len < 2) { } else if (len < 2) {
str = date.getMonth() + 1; str = date.getMonth() + 1;
} else { } else {
str = BI.leftPad(date.getMonth() + 1 + "", 2, "0"); str = leftPad(date.getMonth() + 1 + "", 2, "0");
} }
break; break;
case "d": // 日 case "d": // 日
if (len > 1) { if (len > 1) {
str = BI.leftPad(date.getDate() + "", 2, "0"); str = leftPad(date.getDate() + "", 2, "0");
} else { } else {
str = date.getDate(); str = date.getDate();
} }
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;
} }
if (len > 1) { if (len > 1) {
str = BI.leftPad(hour + "", 2, "0"); str = leftPad(hour + "", 2, "0");
} else { } else {
str = hour; str = hour;
} }
break; break;
case "H": // 时(24) case "H": // 时(24)
if (len > 1) { if (len > 1) {
str = BI.leftPad(date.getHours() + "", 2, "0"); str = leftPad(date.getHours() + "", 2, "0");
} else { } else {
str = date.getHours(); str = date.getHours();
} }
break; break;
case "m": case "m":
if (len > 1) { if (len > 1) {
str = BI.leftPad(date.getMinutes() + "", 2, "0"); str = leftPad(date.getMinutes() + "", 2, "0");
} else { } else {
str = date.getMinutes(); str = date.getMinutes();
} }
break; break;
case "s": case "s":
if (len > 1) { if (len > 1) {
str = BI.leftPad(date.getSeconds() + "", 2, "0"); str = leftPad(date.getSeconds() + "", 2, "0");
} else { } else {
str = date.getSeconds(); str = date.getSeconds();
} }
@ -865,7 +861,7 @@
str = date.getHours() < 12 ? "am" : "pm"; str = date.getHours() < 12 ? "am" : "pm";
break; break;
case "z": case "z":
str = BI.getTimezone(date); str = getTimezone(date);
break; break;
default: default:
str = jfmt.str; str = jfmt.str;
@ -873,23 +869,23 @@
} }
return str; return str;
} }
}; };
BI.object2Number = function (value) { export const object2Number = function (value) {
if (value == null) { if (value == null) {
return 0; return 0;
} }
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);
} }
return parseFloat(str); return parseFloat(str);
}; };
BI.object2Date = function (obj) { export const object2Date = function (obj) {
if (obj == null) { if (obj == null) {
return new Date(); return new Date();
} }
@ -898,27 +894,27 @@
} 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;
} }
return new Date(); return new Date();
}; };
BI.object2Time = function (obj) { export const object2Time = function (obj) {
if (obj == null) { if (obj == null) {
return new Date(); return new Date();
} }
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;
} }
@ -928,11 +924,10 @@
return dt; return dt;
} }
} }
dt = BI.parseDateTime(str, "HH:mm:ss"); dt = parseDateTime(str, "HH:mm:ss");
if (!isInvalidDate(dt)) { if (!isInvalidDate(dt)) {
return dt; return dt;
} }
return new Date(); return new Date();
}; };
})();

25
src/core/func/array.js

@ -2,21 +2,18 @@
* 对数组对象的扩展 * 对数组对象的扩展
* @class Array * @class Array
*/ */
BI._.extend(BI, { export function pushArray(sArray, array) {
sArray.push(...array);
}
pushArray: function (sArray, array) { export function pushDistinct(sArray, obj) {
for (var i = 0; i < array.length; i++) { if (sArray.indexOf(obj) !== -1) {
sArray.push(array[i]);
}
},
pushDistinct: function (sArray, obj) {
if (!BI.contains(sArray, obj)) {
sArray.push(obj); sArray.push(obj);
} }
}, }
pushDistinctArray: function (sArray, array) {
for (var i = 0, len = array.length; i < len; i++) { export function pushDistinctArray(sArray, array) {
BI.pushDistinct(sArray, array[i]); for (let i = 0, len = array.length; i < len; i++) {
} pushDistinct(sArray, array[i]);
} }
}); }

347
src/core/func/date.js

@ -1,16 +1,14 @@
/** Constants used for time computations */ /** Constants used for time computations */
BI.Date = BI.Date || {}; import {getDate, getTime} from "../2.base";
BI.Date.SECOND = 1000;
BI.Date.MINUTE = 60 * BI.Date.SECOND;
BI.Date.HOUR = 60 * BI.Date.MINUTE;
BI.Date.DAY = 24 * BI.Date.HOUR;
BI.Date.WEEK = 7 * BI.Date.DAY;
// Monday first, etc. const SECOND = 1000;
BI.Date._FD = 1; const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
// short month names const DAY = 24 * HOUR;
BI.Date._SMN = [0, const WEEK = 7 * DAY;
const _FD = 1;
const _SMN = [
0,
1, 1,
2, 2,
3, 3,
@ -21,94 +19,126 @@ BI.Date._SMN = [0,
8, 8,
9, 9,
10, 10,
11]; 11
];
/** Adds the number of days array to the Date object. */ const _MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
BI.Date._MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const _OFFSET = [0, -1, -2, -3, -4, -5, -6]; // 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以
// 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以 export const Date = {
BI.Date._OFFSET = [0, -1, -2, -3, -4, -5, -6]; SECOND,
MINUTE,
HOUR,
DAY,
WEEK,
_FD,
_SMN,
_MD,
_OFFSET,
};
BI._.extend(BI, { /**
/**
* 获取时区 * 获取时区
* @returns {String} * @returns {String}
*/ */
getTimezone: function (date) { export function getTimezone(date) {
return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
}, }
/** Returns the number of days in the current month */ /**
getMonthDays: function (date, month) { * Returns the number of days in the current month
var year = date.getFullYear(); */
if (typeof month === "undefined") { export function getMonthDays(date, month = date.getMonth()) {
month = date.getMonth(); 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;
} }
return BI.Date._MD[month]; return _MD[month];
}
}, /**
* 获取每月的最后一天
* @returns {Date}
*/
export function getLastDateOfMont(date) {
return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
}
/** /**
* 获取每月的最后一天 * 获取每月的最后一天
* @returns {Date} * @returns {Date}
*/ */
getLastDateOfMonth: function (date) { export function getLastDateOfMonth(date) {
return BI.getDate(date.getFullYear(), date.getMonth(), BI.getMonthDays(date)); return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
}, }
/**
* Returns the number of day in the year.
* @param date
* @returns {number}
*/
export function getDayOfYear(date) {
const now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
const then = getDate(date.getFullYear(), 0, 0, 0, 0, 0);
const time = now - then;
return Math.floor(time / DAY);
}
/** Returns the number of day in the year. */
getDayOfYear: function (date) {
var now = BI.getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var then = BI.getDate(date.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / BI.Date.DAY);
},
/** Returns the number of the week in year, as defined in ISO 8601. */ /**
getWeekNumber: function (date) { * Returns the number of the week in year, as defined in ISO 8601.
var d = BI.getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); * @param date
var week = d.getDay(); * @returns {number}
var startOfWeek = BI.StartOfWeek % 7; */
var middleDay = (startOfWeek + 3) % 7; export function getWeekNumber(date) {
const d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
const week = d.getDay();
const startOfWeek = BI.StartOfWeek % 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;
}, }
getQuarter: function (date) { export function getQuarter(date) {
return Math.floor(date.getMonth() / 3) + 1; return Math.floor(date.getMonth() / 3) + 1;
}, }
// 离当前时间多少天的时间 /**
getOffsetDate: function (date, offset) { * 离当前时间多少天的时间
return BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) + offset * 864e5); * @param date
}, * @param offset
* @returns {Date}
*/
export function getOffsetDate(date, offset) {
return getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) + offset * 864e5);
}
getOffsetQuarter: function (date, n) { export function getOffsetQuarter(date, n) {
var dt = BI.getDate(BI.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(BI.getDate(dt.getFullYear(), dt.getMonth() + BI.parseInt(n) * 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;
} }
dt.setDate(day); dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n) * 3); dt.setMonth(dt.getMonth() + parseInt(n, 10) * 3);
return dt; return dt;
}, }
// 得到本季度的起始月份 /**
getQuarterStartMonth: function (date) { * 得到本季度的起始月份
var quarterStartMonth = 0; * @param date
var nowMonth = date.getMonth(); * @returns {number}
*/
export function getQuarterStartMonth(date) {
let quarterStartMonth = 0;
const nowMonth = date.getMonth();
if (nowMonth < 3) { if (nowMonth < 3) {
quarterStartMonth = 0; quarterStartMonth = 0;
} }
@ -122,67 +152,96 @@ BI._.extend(BI, {
quarterStartMonth = 9; quarterStartMonth = 9;
} }
return quarterStartMonth; return quarterStartMonth;
}, }
// 获得本季度的起始日期
getQuarterStartDate: function (date) { /**
return BI.getDate(date.getFullYear(), BI.getQuarterStartMonth(date), 1); * 获得本季度的起始日期
}, * @param date
// 得到本季度的结束日期 * @returns {Date}
getQuarterEndDate: function (date) { */
var quarterEndMonth = BI.getQuarterStartMonth(date) + 2; export function getQuarterStartDate(date) {
return BI.getDate(date.getFullYear(), quarterEndMonth, BI.getMonthDays(date, quarterEndMonth)); return getDate(date.getFullYear(), getQuarterStartMonth(date), 1);
}, }
// 指定日期n个月之前或之后的日期 /**
getOffsetMonth: function (date, n) { * 得到本季度的结束日期
var dt = BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); * @param date
var day = dt.getDate(); * @returns {Date}
var monthDay = BI.getMonthDays(BI.getDate(dt.getFullYear(), dt.getMonth() + parseInt(n), 1)); */
export function getQuarterEndDate(date) {
const quarterEndMonth = getQuarterStartMonth(date) + 2;
return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date));
}
/**
* 指定日期n个月之前或之后的日期
* @param date
* @param n
* @returns {Date}
*/
export function getOffsetMonth(date, n) {
const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
let day = dt.getDate();
const monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1));
if (day > monthDay) { if (day > monthDay) {
day = monthDay; day = monthDay;
} }
dt.setDate(day); dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n)); dt.setMonth(dt.getMonth() + parseInt(n, 10));
return dt; return dt;
}, }
// 获得本周的起始日期 /**
getWeekStartDate: function (date) { * 获得本周的起始日期
var w = date.getDay(); * @param date
var startOfWeek = BI.StartOfWeek % 7; * @returns {Date}
return BI.getOffsetDate(date, BI.Date._OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); */
}, export function getWeekStartDate(date) {
// 得到本周的结束日期 const w = date.getDay();
getWeekEndDate: function (date) { const startOfWeek = BI.StartOfWeek % 7;
var w = date.getDay(); return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]);
var startOfWeek = BI.StartOfWeek % 7; }
return BI.getOffsetDate(date, BI.Date._OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6);
},
getFullDayName: function (index) { /**
return [BI.i18nText("BI-Basic_Sunday"), * 得到本周的结束日期
* @param date
* @returns {Date}
*/
export function getWeekEndDate(date) {
const w = date.getDay();
const startOfWeek = BI.StartOfWeek % 7;
return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6);
}
export function getFullDayName(index) {
return [
BI.i18nText("BI-Basic_Sunday"),
BI.i18nText("BI-Basic_Monday"), BI.i18nText("BI-Basic_Monday"),
BI.i18nText("BI-Basic_Tuesday"), BI.i18nText("BI-Basic_Tuesday"),
BI.i18nText("BI-Basic_Wednesday"), BI.i18nText("BI-Basic_Wednesday"),
BI.i18nText("BI-Basic_Thursday"), BI.i18nText("BI-Basic_Thursday"),
BI.i18nText("BI-Basic_Friday"), BI.i18nText("BI-Basic_Friday"),
BI.i18nText("BI-Basic_Saturday"), BI.i18nText("BI-Basic_Saturday"),
BI.i18nText("BI-Basic_Sunday")][index]; BI.i18nText("BI-Basic_Sunday")
}, ][index];
}
getShortDayName: function (index) { export function getShortDayName(index) {
return [BI.i18nText("BI-Basic_Simple_Sunday"), return [
BI.i18nText("BI-Basic_Simple_Sunday"),
BI.i18nText("BI-Basic_Simple_Monday"), BI.i18nText("BI-Basic_Simple_Monday"),
BI.i18nText("BI-Basic_Simple_Tuesday"), BI.i18nText("BI-Basic_Simple_Tuesday"),
BI.i18nText("BI-Basic_Simple_Wednesday"), BI.i18nText("BI-Basic_Simple_Wednesday"),
BI.i18nText("BI-Basic_Simple_Thursday"), BI.i18nText("BI-Basic_Simple_Thursday"),
BI.i18nText("BI-Basic_Simple_Friday"), BI.i18nText("BI-Basic_Simple_Friday"),
BI.i18nText("BI-Basic_Simple_Saturday"), BI.i18nText("BI-Basic_Simple_Saturday"),
BI.i18nText("BI-Basic_Simple_Sunday")][index]; BI.i18nText("BI-Basic_Simple_Sunday")
}, ][index];
}
getMonthName: function (index) { export function getMonthName(index) {
return [BI.i18nText("BI-Basic_January"), return [
BI.i18nText("BI-Basic_January"),
BI.i18nText("BI-Basic_February"), BI.i18nText("BI-Basic_February"),
BI.i18nText("BI-Basic_March"), BI.i18nText("BI-Basic_March"),
BI.i18nText("BI-Basic_April"), BI.i18nText("BI-Basic_April"),
@ -193,42 +252,51 @@ BI._.extend(BI, {
BI.i18nText("BI-Basic_September"), BI.i18nText("BI-Basic_September"),
BI.i18nText("BI-Basic_October"), BI.i18nText("BI-Basic_October"),
BI.i18nText("BI-Basic_November"), BI.i18nText("BI-Basic_November"),
BI.i18nText("BI-Basic_December")][index] BI.i18nText("BI-Basic_December")
}, ][index];
}
getQuarterName: function (index) { export function getQuarterName(index) {
return ["", BI.i18nText("BI-Quarter_1"), return [
"",
BI.i18nText("BI-Quarter_1"),
BI.i18nText("BI-Quarter_2"), BI.i18nText("BI-Quarter_2"),
BI.i18nText("BI-Quarter_3"), BI.i18nText("BI-Quarter_3"),
BI.i18nText("BI-Quarter_4")][index]; BI.i18nText("BI-Quarter_4")
}, ][index];
}
// 格式化打印日期 /**
print: function (date, str) { * 格式化打印日期
var m = date.getMonth(); * @param date
var d = date.getDate(); * @param str
var y = date.getFullYear(); * @returns {*}
var yWith4number = y + ""; */
export function print(date, str) {
const m = date.getMonth();
const d = date.getDate();
const y = date.getFullYear();
let yWith4number = y + "";
while (yWith4number.length < 4) { while (yWith4number.length < 4) {
yWith4number = "0" + yWith4number; yWith4number = "0" + yWith4number;
} }
var wn = BI.getWeekNumber(date); const wn = getWeekNumber(date);
var qr = BI.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 = BI.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"] = BI.getShortDayName(w); // abbreviated weekday name [FIXME: I18N] s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N]
s["%A"] = BI.getFullDayName(w); // full weekday name s["%A"] = getFullDayName(w); // full weekday name
s["%b"] = BI.Date._SMN[m]; // abbreviated month name [FIXME: I18N] s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = BI.getMonthName(m); // full month name s["%B"] = getMonthName(m); // full month name
// FIXME: %c : preferred date and time representation for the current locale // FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31) s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
@ -263,9 +331,9 @@ BI._.extend(BI, {
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;
} }
return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); return /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
@ -298,9 +366,9 @@ BI._.extend(BI, {
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);
@ -308,5 +376,4 @@ BI._.extend(BI, {
} }
return str; return str;
} }
});

126
src/core/func/function.js

@ -2,105 +2,106 @@
* 基本的函数 * 基本的函数
* Created by GUY on 2015/6/24. * Created by GUY on 2015/6/24.
*/ */
BI.Func = BI.Func || {}; import {every, isKey, isArray, toUpperCase, each, stripEL, isNotNull, isNull, isObject} from "../2.base";
BI._.extend(BI.Func, { import {makeFirstPY} from "../utils/chinesePY";
/**
/**
* 创建唯一的名字 * 创建唯一的名字
* @param array * @param array
* @param name * @param name
* @returns {*} * @returns {*}
*/ */
createDistinctName: function (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 (BI.every(array, function (i, item) { if (every(array, function (i, item) {
return BI.isKey(item) ? item !== name : item.name !== name; return isKey(item) ? item !== name : item.name !== name;
})) { })) {
break; break;
} }
name = src + (idx++); name = src + (idx++);
} }
return name; return name;
}, }
/** /**
* 获取字符宽度 * 获取字符宽度
* @param str * @param str
* @return {number} * @return {number}
*/ */
getGBWidth: function (str) { export function getGBWidth(str) {
str = str + ""; str = str + "";
str = str.replace(/[^\x00-\xff]/g, "xx"); str = str.replace(/[^\x00-\xff]/g, "xx");
return Math.ceil(str.length / 2); return Math.ceil(str.length / 2);
}, }
/** /**
* 获取搜索结果 * 获取搜索结果
* @param items * @param items
* @param keyword * @param keyword
* @param param 搜索哪个属性 * @param param 搜索哪个属性
*/ */
getSearchResult: function (items, keyword, param) { export function getSearchResult(items, keyword, param) {
var isArray = BI.isArray(items); const array = isArray(items);
items = isArray ? BI.flatten(items) : items; items = array ? BI.flatten(items) : items;
param || (param = "text"); param || (param = "text");
if (!BI.isKey(keyword)) { if (!isKey(keyword)) {
return { return {
find: items, find: items,
match: isArray ? [] : {} match: array ? [] : {},
}; };
} }
var t, text, py; let t, text, py;
keyword = BI.toUpperCase(keyword); keyword = toUpperCase(keyword);
var matched = isArray ? [] : {}, find = isArray ? [] : {}; const matched = array ? [] : {}, find = array ? [] : {};
BI.each(items, function (i, item) { each(items, function (i, item) {
// 兼容item为null的处理 // 兼容item为null的处理
if (BI.isNull(item)) { if (isNull(item)) {
return; return;
} }
t = BI.stripEL(item); t = stripEL(item);
text = BI.find([t[param], t.text, t.value, t.name, t], function (index, val) { text = [t[param], t.text, t.value, t.name, t].find(isNotNull);
return BI.isNotNull(val);
});
if (BI.isNull(text) || BI.isObject(text)) return; if (isNull(text) || isObject(text)) return;
py = BI.makeFirstPY(text, { py = makeFirstPY(text, {
splitChar: "\u200b" splitChar: "\u200b",
}); });
text = BI.toUpperCase(text); text = toUpperCase(text);
py = BI.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) {
isArray ? matched.push(item) : (matched[i] = item); array ? matched.push(item) : (matched[i] = item);
} else { } else {
isArray ? find.push(item) : (find[i] = item); array ? find.push(item) : (find[i] = item);
} }
// BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 } else { // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件
} else if (pidx = py.indexOf(keyword), (pidx > -1)) { pidx = py.indexOf(keyword);
if (pidx > -1) {
if (text === keyword || keyword.length === text.length) { if (text === keyword || keyword.length === text.length) {
isArray ? matched.push(item) : (matched[i] = item); array ? matched.push(item) : (matched[i] = item);
} else { } else {
isArray ? find.push(item) : (find[i] = item); array ? find.push(item) : (find[i] = item);
}
} }
} }
}); });
return { return {
match: matched, match: matched,
find: find find: find,
}; };
}, }
/** /**
* 获取按GB2312排序的结果 * 获取按GB2312排序的结果
* @param items * @param items
* @param key * @param key
* @return {any[]} * @return {any[]}
*/ */
getSortedResult: function (items, key) { export function getSortedResult(items, key) {
var getTextOfItem = BI.isFunction(key) ? key : const 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];
@ -115,8 +116,8 @@ BI._.extend(BI.Func, {
}; };
return items.sort(function (item1, item2) { return items.sort(function (item1, item2) {
var str1 = getTextOfItem(item1, key); const str1 = getTextOfItem(item1, key);
var str2 = getTextOfItem(item2, key); const str2 = getTextOfItem(item2, key);
if (BI.isNull(str1) && BI.isNull(str2)) { if (BI.isNull(str1) && BI.isNull(str2)) {
return 0; return 0;
} }
@ -129,10 +130,10 @@ BI._.extend(BI.Func, {
if (str1 === str2) { if (str1 === str2) {
return 0; return 0;
} }
var len1 = str1.length, len2 = str2.length; const 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]; const char1 = str1[i];
var char2 = str2[i]; const 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]);
@ -140,29 +141,34 @@ BI._.extend(BI.Func, {
} }
return len1 - len2; return len1 - len2;
}); });
} }
});
BI._.extend(BI, { export function beforeFunc(sFunc, func) {
beforeFunc: function (sFunc, func) { const __self = sFunc;
var __self = sFunc;
return function () { return function () {
if (func.apply(sFunc, arguments) === false) { if (func.apply(sFunc, arguments) === false) {
return false; return false;
} }
return __self.apply(sFunc, arguments); return __self.apply(sFunc, arguments);
}; };
}, }
afterFunc: function (sFunc, func) { export function afterFunc(sFunc, func) {
var __self = sFunc; const __self = sFunc;
return function () { return function () {
var ret = __self.apply(sFunc, arguments); const ret = __self.apply(sFunc, arguments);
if (ret === false) { if (ret === false) {
return false; return false;
} }
func.apply(sFunc, arguments); func.apply(sFunc, arguments);
return ret; return ret;
}; };
} }
});
export const Func = {
createDistinctName,
getGBWidth,
getSearchResult,
getSortedResult,
};

23
src/core/func/index.js

@ -0,0 +1,23 @@
export * from "./alias";
export * from "./array";
export * from "./date";
export * from "./function";
export * from "./number";
export * from "./string";
// need delete
import * as _alias from "./alias";
import * as _array from "./array";
import * as _date from "./date";
import * as _function from "./function";
import * as _number from "./number";
import * as _string from "./string";
Object.assign(BI, {
..._alias,
..._array,
..._date,
..._function,
..._number,
..._string,
});

76
src/core/func/number.js

@ -1,6 +1,5 @@
BI._.extend(BI, { // 给Number类型增加一个add方法,调用起来更加方便。
// 给Number类型增加一个add方法,调用起来更加方便。 export function add(num, arg) {
add: function (num, arg) {
return accAdd(arg, num); return accAdd(arg, num);
/** /**
@ -9,8 +8,8 @@ BI._.extend(BI, {
** 调用accAdd(arg1,arg2) ** 调用accAdd(arg1,arg2)
** 返回值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) {
@ -24,7 +23,7 @@ BI._.extend(BI, {
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); const 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;
@ -38,10 +37,10 @@ BI._.extend(BI, {
} }
return (arg1 + arg2) / m; return (arg1 + arg2) / m;
} }
}, }
// 给Number类型增加一个sub方法,调用起来更加方便。 // 给Number类型增加一个sub方法,调用起来更加方便。
sub: function (num, arg) { export function sub(num, arg) {
return accSub(num, arg); return accSub(num, arg);
/** /**
@ -50,8 +49,8 @@ BI._.extend(BI, {
** 调用accSub(arg1,arg2) ** 调用accSub(arg1,arg2)
** 返回值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) {
@ -66,10 +65,10 @@ BI._.extend(BI, {
n = (r1 >= r2) ? r1 : r2; n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n); return ((arg1 * m - arg2 * m) / m).toFixed(n);
} }
}, }
// 给Number类型增加一个mul方法,调用起来更加方便。 // 给Number类型增加一个mul方法,调用起来更加方便。
mul: function (num, arg) { export function mul(num, arg) {
return accMul(arg, num); return accMul(arg, num);
/** /**
@ -78,8 +77,8 @@ BI._.extend(BI, {
** 调用accMul(arg1,arg2) ** 调用accMul(arg1,arg2)
** 返回值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) {
@ -90,67 +89,66 @@ BI._.extend(BI, {
} }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
} }
}, }
// 给Number类型增加一个div方法,调用起来更加方便。 // 给Number类型增加一个div方法,调用起来更加方便。
div: function (num, arg) { export function div(num, arg) {
return accDivide(num, arg); return accDivide(num, arg);
/** /**
* Return digits length of a number * Return digits length of a number
* @param {*number} num Input number * @param {*number} num Input number
*/ */
function digitLength (num) { function digitLength(num) {
// Get digit length of e // Get digit length of e
var eSplit = num.toString().split(/[eE]/); const eSplit = num.toString().split(/[eE]/);
var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); const len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0));
return len > 0 ? len : 0; return len > 0 ? len : 0;
} }
/** /**
* 把小数转成整数支持科学计数法如果是小数则放大成整数 * 把小数转成整数支持科学计数法如果是小数则放大成整数
* @param {*number} num 输入数 * @param {*number} num 输入数
*/ */
function float2Fixed (num) { function float2Fixed(num) {
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); const dLen = digitLength(num);
return dLen > 0 ? num * Math.pow(10, dLen) : num; return dLen > 0 ? num * Math.pow(10, dLen) : num;
} }
/** /**
* 精确乘法 * 精确乘法
*/ */
function times (num1, num2) { function times(num1, num2) {
var others = []; const 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); const num1Changed = float2Fixed(num1);
var num2Changed = float2Fixed(num2); const num2Changed = float2Fixed(num2);
var baseNum = digitLength(num1) + digitLength(num2); const baseNum = digitLength(num1) + digitLength(num2);
var leftValue = num1Changed * num2Changed; const leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum); return leftValue / Math.pow(10, baseNum);
} }
/** /**
* 精确除法 * 精确除法
*/ */
function accDivide (num1, num2) { function accDivide(num1, num2) {
var others = []; const 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); const num1Changed = float2Fixed(num1);
var num2Changed = float2Fixed(num2); const 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)));
} }
} }
});

70
src/core/func/string.js

@ -1,61 +1,58 @@
/** import {isString} from "../2.base";
* 对字符串对象的扩展
* @class String
*/
BI._.extend(BI, {
/** /**
* 判断字符串是否已指定的字符串开始 * 判断字符串是否已指定的字符串开始
* @param str source字符串 * @param str source字符串
* @param {String} startTag 指定的开始字符串 * @param {String} startTag 指定的开始字符串
* @return {Boolean} 如果字符串以指定字符串开始则返回true否则返回false * @return {Boolean} 如果字符串以指定字符串开始则返回true否则返回false
*/ */
startWith: function (str, startTag) { export function startWith(str, startTag) {
str = str || ""; str = str || "";
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;
}, }
/**
/**
* 判断字符串是否以指定的字符串结束 * 判断字符串是否以指定的字符串结束
* @param str source字符串 * @param str source字符串
* @param {String} endTag 指定的字符串 * @param {String} endTag 指定的字符串
* @return {Boolean} 如果字符串以指定字符串结束则返回true否则返回false * @return {Boolean} 如果字符串以指定字符串结束则返回true否则返回false
*/ */
endWith: function (str, endTag) { export function endWith(str, endTag) {
if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) { if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
return false; return false;
} }
return str.substring(str.length - endTag.length) == endTag; return str.substring(str.length - endTag.length) == endTag;
}, }
/** /**
* 获取url中指定名字的参数 * 获取url中指定名字的参数
* @param str source字符串 * @param str source字符串
* @param {String} name 参数的名字 * @param {String} name 参数的名字
* @return {String} 参数的值 * @return {String} 参数的值
*/ */
getQuery: function (str, name) { export function getQuery(str, name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = str.substr(str.indexOf("?") + 1).match(reg); const r = str.substr(str.indexOf("?") + 1).match(reg);
if (r) { if (r) {
return unescape(r[2]); return unescape(r[2]);
} }
return null; return null;
}, }
/** /**
* 给url加上给定的参数 * 给url加上给定的参数
* @param str source字符串 * @param str source字符串
* @param {Object} paras 参数对象是一个键值对对象 * @param {Object} paras 参数对象是一个键值对对象
* @return {String} 添加了给定参数的url * @return {String} 添加了给定参数的url
*/ */
appendQuery: function (str, paras) { 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 += "?";
@ -66,51 +63,53 @@ BI._.extend(BI, {
src += "&"; src += "&";
} }
BI._.each(paras, function (value, name) { BI._.each(paras, function (value, name) {
if (typeof(name) === "string") { if (typeof (name) === "string") {
src += name + "=" + value + "&"; src += name + "=" + value + "&";
} }
}); });
src = src.substr(0, src.length - 1); src = src.substr(0, src.length - 1);
return src; return src;
}, }
/**
/**
* 将所有符合第一个字符串所表示的字符串替换成为第二个字符串 * 将所有符合第一个字符串所表示的字符串替换成为第二个字符串
* @param str source字符串 * @param str source字符串
* @param {String} s1 要替换的字符串的正则表达式 * @param {String} s1 要替换的字符串的正则表达式
* @param {String} s2 替换的结果字符串 * @param {String} s2 替换的结果字符串
* @returns {String} 替换后的字符串 * @returns {String} 替换后的字符串
*/ */
replaceAll: function (str, s1, s2) { export function replaceAll(str, s1, s2) {
return BI.isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str; return isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str;
}, }
/**
/**
* 总是让字符串以指定的字符开头 * 总是让字符串以指定的字符开头
* @param str source字符串 * @param str source字符串
* @param {String} start 指定的字符 * @param {String} start 指定的字符
* @returns {String} 以指定字符开头的字符串 * @returns {String} 以指定字符开头的字符串
*/ */
perfectStart: function (str, start) { export function perfectStart(str, start) {
if (BI.startWith(str, start)) { if (BI.startWith(str, start)) {
return str; return str;
} }
return start + str; return start + str;
}, }
/** /**
* 获取字符串中某字符串的所有项位置数组 * 获取字符串中某字符串的所有项位置数组
* @param str source字符串 * @param str source字符串
* @param {String} sub 子字符串 * @param {String} sub 子字符串
* @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组 * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组
*/ */
allIndexOf: function (str, sub) { export function allIndexOf(str, sub) {
if (typeof sub !== "string") { if (typeof sub !== "string") {
return []; return [];
} }
var location = []; const location = [];
var offset = 0; let offset = 0;
while (str.length > 0) { while (str.length > 0) {
var loc = str.indexOf(sub); const loc = str.indexOf(sub);
if (loc === -1) { if (loc === -1) {
break; break;
} }
@ -119,5 +118,4 @@ BI._.extend(BI, {
offset += loc + sub.length; offset += loc + sub.length;
} }
return location; return location;
} }
});

14
src/core/index.js

@ -1,4 +1,4 @@
import { shortcut } from "./decorator"; import {shortcut} from "./decorator";
import OB from "./3.ob"; import OB from "./3.ob";
import Widget from "./4.widget"; import Widget from "./4.widget";
import Action from "./action/action"; import Action from "./action/action";
@ -16,6 +16,7 @@ import PopoverController from "./controller/controller.popover";
import ResizeController from "./controller/controller.resizer"; import ResizeController from "./controller/controller.resizer";
import TooltipsController from "./controller/controller.tooltips"; import TooltipsController from "./controller/controller.tooltips";
import StyleLoaderManager from "./loader/loader.style"; import StyleLoaderManager from "./loader/loader.style";
import "./h";
import ShowListener from "./listener/listener.show"; import ShowListener from "./listener/listener.show";
BI.extend(BI, { BI.extend(BI, {
@ -39,9 +40,10 @@ BI.extend(BI, {
ShowListener, ShowListener,
}); });
export * from './2.base'; export * from "./2.base";
export * from './4.widget'; export * from "./4.widget";
export * from './5.inject'; export * from "./5.inject";
export * from "./func";
export { export {
shortcut, shortcut,
@ -62,5 +64,5 @@ export {
ResizeController, ResizeController,
TooltipsController, TooltipsController,
StyleLoaderManager, StyleLoaderManager,
ShowListener, ShowListener
} };

59
src/core/platform/web/detectElementResize.js

@ -323,7 +323,22 @@ var ResizeObserverPolyfill = (function (exports) {
}; };
var CATCH_PERIOD = 250; var CATCH_PERIOD = 250;
var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true };
var events = ['resize', 'load', 'transitionend', 'animationend', 'animationstart', 'animationiteration', 'keyup', 'keydown', 'mouseup', 'mousedown', 'mouseover', 'mouseout', 'blur', 'focus']; var events = [
'resize',
'load',
'transitionend',
'animationend',
'animationstart',
'animationiteration',
'keyup',
'keydown',
'mouseup',
'mousedown',
'mouseover',
'mouseout',
'blur',
'focus'
];
var time = function (timeout) { var time = function (timeout) {
if (timeout === void 0) { if (timeout === void 0) {
timeout = 0; timeout = 0;
@ -412,14 +427,17 @@ var ResizeObserverPolyfill = (function (exports) {
}; };
var skipNotifyOnElement = function (target) { var skipNotifyOnElement = function (target) {
return !isSVG(target) && !isReplacedElement(target) && getComputedStyle(target).display === 'inline'; return !isSVG(target)
&& !isReplacedElement(target)
&& getComputedStyle(target).display === 'inline';
}; };
var ResizeObservation = (function () { var ResizeObservation = (function () {
function ResizeObservation(target, observedBox) { function ResizeObservation(target, observedBox) {
this.target = target; this.target = target;
this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX;
this.lastReportedSize = { this.lastReportedSize = {
inlineSize: -1, blockSize: -1 inlineSize: -1,
blockSize: -1
}; };
} }
@ -428,7 +446,8 @@ var ResizeObserverPolyfill = (function (exports) {
if (skipNotifyOnElement(this.target)) { if (skipNotifyOnElement(this.target)) {
this.lastReportedSize = size; this.lastReportedSize = size;
} }
if (this.lastReportedSize.inlineSize !== size.inlineSize || this.lastReportedSize.blockSize !== size.blockSize) { if (this.lastReportedSize.inlineSize !== size.inlineSize
|| this.lastReportedSize.blockSize !== size.blockSize) {
return true; return true;
} }
return false; return false;
@ -534,21 +553,12 @@ var ResizeObserverPolyfill = (function (exports) {
return ResizeObserver; return ResizeObserver;
}()); }());
exports.ResizeObserver = ResizeObserver; return ResizeObserver;
exports.ResizeObserverEntry = ResizeObserverEntry; })();
exports.ResizeObserverSize = ResizeObserverSize;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({});
var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObserver;
!(function () { var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;
var addResizeListener = function (element, fn) { var addResizeListener = function (element, fn) {
if (ResizeObserver) { if (ResizeObserver) {
if (!element.__resizeObserver__) { if (!element.__resizeObserver__) {
var resizeObserver = new ResizeObserver(function () { var resizeObserver = new ResizeObserver(function () {
@ -564,8 +574,8 @@ var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObser
} }
element.__resizeListeners__.push(fn); element.__resizeListeners__.push(fn);
} }
}; };
var removeResizeListener = function (element, fn) { var removeResizeListener = function (element, fn) {
if (ResizeObserver) { if (ResizeObserver) {
if (BI.isNull(fn)) { if (BI.isNull(fn)) {
element.__resizeListeners__ = []; element.__resizeListeners__ = [];
@ -582,9 +592,9 @@ var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObser
} }
} }
} }
}; };
BI.ResizeDetector = { export const ResizeDetector = {
addResizeListener: function (widget, fn) { addResizeListener: function (widget, fn) {
addResizeListener(widget.element[0], fn); addResizeListener(widget.element[0], fn);
return function () { return function () {
@ -593,5 +603,8 @@ var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObser
}, removeResizeListener: function (widget, fn) { }, removeResizeListener: function (widget, fn) {
removeResizeListener(widget.element[0], fn); removeResizeListener(widget.element[0], fn);
} }
}; };
})();
Object.assign(BI, {
ResizeDetector
});

39
src/core/utils/chinesePY.js

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save