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. 26
      src/core/2.base.js
  2. 4
      src/core/func/__test__/function.test.js
  3. 1661
      src/core/func/alias.js
  4. 29
      src/core/func/array.js
  5. 615
      src/core/func/date.js
  6. 300
      src/core/func/function.js
  7. 23
      src/core/func/index.js
  8. 272
      src/core/func/number.js
  9. 224
      src/core/func/string.js
  10. 14
      src/core/index.js
  11. 123
      src/core/platform/web/detectElementResize.js
  12. 863
      src/core/utils/chinesePY.js

26
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) {
@ -886,7 +893,7 @@ export const nextTick = (function () {
}; };
})(); })();
BI._.extend(BI, { nextTick }); BI._.extend(BI, { nextTick });
// 数字相关方法 // 数字相关方法
BI._.each(["random"], function (name) { BI._.each(["random"], function (name) {
@ -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");
}); });

1661
src/core/func/alias.js

File diff suppressed because it is too large Load Diff

29
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]); sArray.push(obj);
}
},
pushDistinct: function (sArray, obj) {
if (!BI.contains(sArray, obj)) {
sArray.push(obj);
}
},
pushDistinctArray: function (sArray, array) {
for (var i = 0, len = array.length; i < len; i++) {
BI.pushDistinct(sArray, array[i]);
}
} }
}); }
export function pushDistinctArray(sArray, array) {
for (let i = 0, len = array.length; i < len; i++) {
pushDistinct(sArray, array[i]);
}
}

615
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,292 +19,361 @@ BI.Date._SMN = [0,
8, 8,
9, 9,
10, 10,
11]; 11
];
const _MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const _OFFSET = [0, -1, -2, -3, -4, -5, -6]; // 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以
/** Adds the number of days array to the Date object. */ export const Date = {
BI.Date._MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; SECOND,
MINUTE,
HOUR,
DAY,
WEEK,
_FD,
_SMN,
_MD,
_OFFSET,
};
// 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以 /**
BI.Date._OFFSET = [0, -1, -2, -3, -4, -5, -6]; * 获取时区
* @returns {String}
*/
export function getTimezone(date) {
return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
}
BI._.extend(BI, { /**
/** * Returns the number of days in the current month
* 获取时区 */
* @returns {String} export function getMonthDays(date, month = date.getMonth()) {
*/ const year = date.getFullYear();
getTimezone: function (date) { if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) {
return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); return 29;
}, }
return _MD[month];
}
/** Returns the number of days in the current month */ /**
getMonthDays: function (date, month) { * 获取每月的最后一天
var year = date.getFullYear(); * @returns {Date}
if (typeof month === "undefined") { */
month = date.getMonth(); export function getLastDateOfMont(date) {
} return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
if (((0 == (year % 4)) && ((0 != (year % 100)) || (0 == (year % 400)))) && month == 1) { }
return 29;
}
return BI.Date._MD[month];
}, /**
* 获取每月的最后一天
* @returns {Date}
*/
export function getLastDateOfMonth(date) {
return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
}
/** /**
* 获取每月的最后一天 * Returns the number of day in the year.
* @returns {Date} * @param date
*/ * @returns {number}
getLastDateOfMonth: function (date) { */
return BI.getDate(date.getFullYear(), date.getMonth(), BI.getMonthDays(date)); 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) {
middleDay = middleDay || 7; const d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
// 偏移到周周首之前需要多少天 const week = d.getDay();
var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); const startOfWeek = BI.StartOfWeek % 7;
var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); let middleDay = (startOfWeek + 3) % 7;
d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); middleDay = middleDay || 7;
var ms = d.valueOf(); // 偏移到周周首之前需要多少天
d.setMonth(0); const offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek);
d.setDate(1); const offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek);
return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount);
}, const ms = d.valueOf();
d.setMonth(0);
d.setDate(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}
if (nowMonth < 3) { */
quarterStartMonth = 0; export function getQuarterStartMonth(date) {
} let quarterStartMonth = 0;
if (2 < nowMonth && nowMonth < 6) { const nowMonth = date.getMonth();
quarterStartMonth = 3; if (nowMonth < 3) {
} quarterStartMonth = 0;
if (5 < nowMonth && nowMonth < 9) { }
quarterStartMonth = 6; if (2 < nowMonth && nowMonth < 6) {
} quarterStartMonth = 3;
if (nowMonth > 8) { }
quarterStartMonth = 9; if (5 < nowMonth && nowMonth < 9) {
} quarterStartMonth = 6;
return quarterStartMonth; }
}, if (nowMonth > 8) {
// 获得本季度的起始日期 quarterStartMonth = 9;
getQuarterStartDate: function (date) { }
return BI.getDate(date.getFullYear(), BI.getQuarterStartMonth(date), 1); return quarterStartMonth;
}, }
// 得到本季度的结束日期
getQuarterEndDate: function (date) {
var quarterEndMonth = BI.getQuarterStartMonth(date) + 2;
return BI.getDate(date.getFullYear(), quarterEndMonth, BI.getMonthDays(date, quarterEndMonth));
},
// 指定日期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)); */
if (day > monthDay) { export function getQuarterStartDate(date) {
day = monthDay; return getDate(date.getFullYear(), getQuarterStartMonth(date), 1);
} }
dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n));
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 getQuarterEndDate(date) {
// 得到本周的结束日期 const quarterEndMonth = getQuarterStartMonth(date) + 2;
getWeekEndDate: function (date) { return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date));
var w = date.getDay(); }
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"), * 指定日期n个月之前或之后的日期
BI.i18nText("BI-Basic_Monday"), * @param date
BI.i18nText("BI-Basic_Tuesday"), * @param n
BI.i18nText("BI-Basic_Wednesday"), * @returns {Date}
BI.i18nText("BI-Basic_Thursday"), */
BI.i18nText("BI-Basic_Friday"), export function getOffsetMonth(date, n) {
BI.i18nText("BI-Basic_Saturday"), const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
BI.i18nText("BI-Basic_Sunday")][index]; let day = dt.getDate();
}, const monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1));
if (day > monthDay) {
day = monthDay;
}
dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n, 10));
return dt;
}
getShortDayName: function (index) { /**
return [BI.i18nText("BI-Basic_Simple_Sunday"), * 获得本周的起始日期
BI.i18nText("BI-Basic_Simple_Monday"), * @param date
BI.i18nText("BI-Basic_Simple_Tuesday"), * @returns {Date}
BI.i18nText("BI-Basic_Simple_Wednesday"), */
BI.i18nText("BI-Basic_Simple_Thursday"), export function getWeekStartDate(date) {
BI.i18nText("BI-Basic_Simple_Friday"), const w = date.getDay();
BI.i18nText("BI-Basic_Simple_Saturday"), const startOfWeek = BI.StartOfWeek % 7;
BI.i18nText("BI-Basic_Simple_Sunday")][index]; return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]);
}, }
getMonthName: function (index) { /**
return [BI.i18nText("BI-Basic_January"), * 得到本周的结束日期
BI.i18nText("BI-Basic_February"), * @param date
BI.i18nText("BI-Basic_March"), * @returns {Date}
BI.i18nText("BI-Basic_April"), */
BI.i18nText("BI-Basic_May"), export function getWeekEndDate(date) {
BI.i18nText("BI-Basic_June"), const w = date.getDay();
BI.i18nText("BI-Basic_July"), const startOfWeek = BI.StartOfWeek % 7;
BI.i18nText("BI-Basic_August"), return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6);
BI.i18nText("BI-Basic_September"), }
BI.i18nText("BI-Basic_October"),
BI.i18nText("BI-Basic_November"),
BI.i18nText("BI-Basic_December")][index]
},
getQuarterName: function (index) { export function getFullDayName(index) {
return ["", BI.i18nText("BI-Quarter_1"), return [
BI.i18nText("BI-Quarter_2"), BI.i18nText("BI-Basic_Sunday"),
BI.i18nText("BI-Quarter_3"), BI.i18nText("BI-Basic_Monday"),
BI.i18nText("BI-Quarter_4")][index]; BI.i18nText("BI-Basic_Tuesday"),
}, BI.i18nText("BI-Basic_Wednesday"),
BI.i18nText("BI-Basic_Thursday"),
BI.i18nText("BI-Basic_Friday"),
BI.i18nText("BI-Basic_Saturday"),
BI.i18nText("BI-Basic_Sunday")
][index];
}
// 格式化打印日期 export function getShortDayName(index) {
print: function (date, str) { return [
var m = date.getMonth(); BI.i18nText("BI-Basic_Simple_Sunday"),
var d = date.getDate(); BI.i18nText("BI-Basic_Simple_Monday"),
var y = date.getFullYear(); BI.i18nText("BI-Basic_Simple_Tuesday"),
var yWith4number = y + ""; BI.i18nText("BI-Basic_Simple_Wednesday"),
while (yWith4number.length < 4) { BI.i18nText("BI-Basic_Simple_Thursday"),
yWith4number = "0" + yWith4number; BI.i18nText("BI-Basic_Simple_Friday"),
} BI.i18nText("BI-Basic_Simple_Saturday"),
var wn = BI.getWeekNumber(date); BI.i18nText("BI-Basic_Simple_Sunday")
var qr = BI.getQuarter(date); ][index];
var w = date.getDay(); }
var s = {};
var hr = date.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = BI.getDayOfYear(date);
if (ir == 0) {
ir = 12;
}
var min = date.getMinutes();
var sec = date.getSeconds();
s["%a"] = BI.getShortDayName(w); // abbreviated weekday name [FIXME: I18N]
s["%A"] = BI.getFullDayName(w); // full weekday name
s["%b"] = BI.Date._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = BI.getMonthName(m); // full month name
// FIXME: %c : preferred date and time representation for the current locale
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["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr + ""; // hour, range 0 to 23 (24h format)
s["%l"] = ir + ""; // hour, range 1 to 12 (12h format)
s["%X"] = (m < 9) ? ("0" + (1 + m)) : (1 + m); // month, range 01 to 12
s["%x"] = m + 1; // month, range 1 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(date.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = yWith4number.substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = yWith4number; // year with the century
s["%%"] = "%"; // a literal '%' character
s["%q"] = "0" + qr;
s["%Q"] = qr;
var re = /%./g; export function getMonthName(index) {
BI.isKhtml = BI.isKhtml || function () { return [
if(!_global.navigator) { BI.i18nText("BI-Basic_January"),
return false; BI.i18nText("BI-Basic_February"),
} BI.i18nText("BI-Basic_March"),
return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); BI.i18nText("BI-Basic_April"),
}; BI.i18nText("BI-Basic_May"),
BI.i18nText("BI-Basic_June"),
BI.i18nText("BI-Basic_July"),
BI.i18nText("BI-Basic_August"),
BI.i18nText("BI-Basic_September"),
BI.i18nText("BI-Basic_October"),
BI.i18nText("BI-Basic_November"),
BI.i18nText("BI-Basic_December")
][index];
}
// 包含年周的格式化,ISO8601标准周的计数会影响年 export function getQuarterName(index) {
if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) { return [
switch (wn) { "",
// 如果周数是1,但是当前却在12月,表示此周数为下一年的 BI.i18nText("BI-Quarter_1"),
case 1: BI.i18nText("BI-Quarter_2"),
if (m === 11) { BI.i18nText("BI-Quarter_3"),
s["%y"] = parseInt(s["%y"]) + 1; BI.i18nText("BI-Quarter_4")
s["%Y"] = parseInt(s["%Y"]) + 1; ][index];
} }
break;
// 如果周数是53,但是当前却在1月,表示此周数为上一年的
case 53:
if (m === 0) {
s["%y"] = parseInt(s["%y"]) - 1;
s["%Y"] = parseInt(s["%Y"]) - 1;
}
break;
default:
break;
}
}
if (!BI.isKhtml()) { /**
return str.replace(re, function (par) { * 格式化打印日期
return s[par] || par; * @param date
}); * @param str
* @returns {*}
*/
export function print(date, str) {
const m = date.getMonth();
const d = date.getDate();
const y = date.getFullYear();
let yWith4number = y + "";
while (yWith4number.length < 4) {
yWith4number = "0" + yWith4number;
}
const wn = getWeekNumber(date);
const qr = getQuarter(date);
const w = date.getDay();
const s = {};
const hr = date.getHours();
const pm = (hr >= 12);
let ir = (pm) ? (hr - 12) : hr;
const dy = getDayOfYear(date);
if (ir === 0) {
ir = 12;
}
const min = date.getMinutes();
const sec = date.getSeconds();
s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N]
s["%A"] = getFullDayName(w); // full weekday name
s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = getMonthName(m); // full month name
// FIXME: %c : preferred date and time representation for the current locale
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["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr + ""; // hour, range 0 to 23 (24h format)
s["%l"] = ir + ""; // hour, range 1 to 12 (12h format)
s["%X"] = (m < 9) ? ("0" + (1 + m)) : (1 + m); // month, range 01 to 12
s["%x"] = m + 1; // month, range 1 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(date.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = yWith4number.substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = yWith4number; // year with the century
s["%%"] = "%"; // a literal '%' character
s["%q"] = "0" + qr;
s["%Q"] = qr;
let re = /%./g;
BI.isKhtml = BI.isKhtml || function () {
if (!_global.navigator) {
return false;
} }
var a = str.match(re); return /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
for (var i = 0; i < a.length; i++) { };
var tmp = s[a[i]];
if (tmp) { // 包含年周的格式化,ISO8601标准周的计数会影响年
re = new RegExp(a[i], "g"); if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) {
str = str.replace(re, tmp); switch (wn) {
} // 如果周数是1,但是当前却在12月,表示此周数为下一年的
case 1:
if (m === 11) {
s["%y"] = parseInt(s["%y"]) + 1;
s["%Y"] = parseInt(s["%Y"]) + 1;
}
break;
// 如果周数是53,但是当前却在1月,表示此周数为上一年的
case 53:
if (m === 0) {
s["%y"] = parseInt(s["%y"]) - 1;
s["%Y"] = parseInt(s["%Y"]) - 1;
}
break;
default:
break;
} }
}
return str; if (!BI.isKhtml()) {
return str.replace(re, function (par) {
return s[par] || par;
});
} }
}); const a = str.match(re);
for (let i = 0; i < a.length; i++) {
const tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], "g");
str = str.replace(re, tmp);
}
}
return str;
}

300
src/core/func/function.js

@ -2,167 +2,173 @@
* 基本的函数 * 基本的函数
* 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 name * @param array
* @returns {*} * @param name
*/ * @returns {*}
createDistinctName: function (array, name) { */
var src = name, idx = 1; export function createDistinctName(array, name) {
name = name || ""; let src = name, idx = 1;
while (true) { name = name || "";
if (BI.every(array, function (i, item) { while (true) {
return BI.isKey(item) ? item !== name : item.name !== name; if (every(array, function (i, item) {
})) { return isKey(item) ? item !== name : item.name !== name;
break; })) {
} break;
name = src + (idx++);
} }
return name; name = src + (idx++);
}, }
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 ? [] : {},
}; };
}
let t, text, py;
keyword = toUpperCase(keyword);
const matched = array ? [] : {}, find = array ? [] : {};
each(items, function (i, item) {
// 兼容item为null的处理
if (isNull(item)) {
return;
} }
var t, text, py; t = stripEL(item);
keyword = BI.toUpperCase(keyword); text = [t[param], t.text, t.value, t.name, t].find(isNotNull);
var matched = isArray ? [] : {}, find = isArray ? [] : {};
BI.each(items, function (i, item) {
// 兼容item为null的处理
if (BI.isNull(item)) {
return;
}
t = BI.stripEL(item);
text = BI.find([t[param], t.text, t.value, t.name, t], function (index, val) {
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 { });
match: matched, return {
find: find match: matched,
}; find: find,
}, };
}
/**
* 获取按GB2312排序的结果
* @param items
* @param key
* @return {any[]}
*/
getSortedResult: function (items, key) {
var getTextOfItem = BI.isFunction(key) ? key :
function (item, key) {
if (BI.isNotNull(key)) {
return item[key];
}
if (BI.isNotNull(item.text)) {
return item.text;
}
if (BI.isNotNull(item.value)) {
return item.value;
}
return item;
};
return items.sort(function (item1, item2) { /**
var str1 = getTextOfItem(item1, key); * 获取按GB2312排序的结果
var str2 = getTextOfItem(item2, key); * @param items
if (BI.isNull(str1) && BI.isNull(str2)) { * @param key
return 0; * @return {any[]}
} */
if (BI.isNull(str1)) { export function getSortedResult(items, key) {
return -1; const getTextOfItem = BI.isFunction(key) ? key :
} function (item, key) {
if (BI.isNull(str2)) { if (BI.isNotNull(key)) {
return 1; return item[key];
}
if (str1 === str2) {
return 0;
} }
var len1 = str1.length, len2 = str2.length; if (BI.isNotNull(item.text)) {
for (var i = 0; i < len1 && i < len2; i++) { return item.text;
var char1 = str1[i];
var char2 = str2[i];
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 len1 - len2; if (BI.isNotNull(item.value)) {
}); return item.value;
}
});
BI._.extend(BI, {
beforeFunc: function (sFunc, func) {
var __self = sFunc;
return function () {
if (func.apply(sFunc, arguments) === false) {
return false;
} }
return __self.apply(sFunc, arguments); return item;
}; };
},
afterFunc: function (sFunc, func) { return items.sort(function (item1, item2) {
var __self = sFunc; const str1 = getTextOfItem(item1, key);
return function () { const str2 = getTextOfItem(item2, key);
var ret = __self.apply(sFunc, arguments); if (BI.isNull(str1) && BI.isNull(str2)) {
if (ret === false) { return 0;
return false; }
if (BI.isNull(str1)) {
return -1;
}
if (BI.isNull(str2)) {
return 1;
}
if (str1 === str2) {
return 0;
}
const len1 = str1.length, len2 = str2.length;
for (let i = 0; i < len1 && i < len2; i++) {
const char1 = str1[i];
const char2 = str2[i];
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]);
} }
func.apply(sFunc, arguments); }
return ret; return len1 - len2;
}; });
} }
});
export function beforeFunc(sFunc, func) {
const __self = sFunc;
return function () {
if (func.apply(sFunc, arguments) === false) {
return false;
}
return __self.apply(sFunc, arguments);
};
}
export function afterFunc(sFunc, func) {
const __self = sFunc;
return function () {
const ret = __self.apply(sFunc, arguments);
if (ret === false) {
return false;
}
func.apply(sFunc, arguments);
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,
});

272
src/core/func/number.js

@ -1,156 +1,154 @@
BI._.extend(BI, { // 给Number类型增加一个add方法,调用起来更加方便。
// 给Number类型增加一个add方法,调用起来更加方便。 export function add(num, arg) {
add: function (num, arg) { return accAdd(arg, num);
return accAdd(arg, num);
/** /**
** 加法函数用来得到精确的加法结果 ** 加法函数用来得到精确的加法结果
** 说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显这个函数返回较为精确的加法结果 ** 说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显这个函数返回较为精确的加法结果
** 调用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) {
r1 = 0; r1 = 0;
} }
try { try {
r2 = arg2.toString().split(".")[1].length; r2 = arg2.toString().split(".")[1].length;
} catch (e) { } catch (e) {
r2 = 0; r2 = 0;
} }
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(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * cm;
arg2 = Number(arg2.toString().replace(".", ""));
}
} else {
arg1 = Number(arg1.toString().replace(".", "")); arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * cm;
arg2 = Number(arg2.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", ""));
} }
return (arg1 + arg2) / m; } else {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", ""));
} }
}, 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);
/** /**
** 减法函数用来得到精确的减法结果 ** 减法函数用来得到精确的减法结果
** 说明javascript的减法结果会有误差在两个浮点数相减的时候会比较明显这个函数返回较为精确的减法结果 ** 说明javascript的减法结果会有误差在两个浮点数相减的时候会比较明显这个函数返回较为精确的减法结果
** 调用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) {
r1 = 0; r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2)); // last modify by deeka //动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
} }
}, try {
r2 = arg2.toString().split(".")[1].length;
// 给Number类型增加一个mul方法,调用起来更加方便。 } catch (e) {
mul: function (num, arg) { r2 = 0;
return accMul(arg, num);
/**
** 乘法函数用来得到精确的乘法结果
** 说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显这个函数返回较为精确的乘法结果
** 调用accMul(arg1,arg2)
** 返回值arg1乘以 arg2的精确结果
**/
function accMul (arg1, arg2) {
var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {
}
try {
m += s2.split(".")[1].length;
} catch (e) {
}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
} }
}, m = Math.pow(10, Math.max(r1, r2)); // last modify by deeka //动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
}
// 给Number类型增加一个div方法,调用起来更加方便。 // 给Number类型增加一个mul方法,调用起来更加方便。
div: function (num, arg) { export function mul(num, arg) {
return accDivide(num, arg); return accMul(arg, num);
/** /**
* Return digits length of a number ** 乘法函数用来得到精确的乘法结果
* @param {*number} num Input number ** 说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显这个函数返回较为精确的乘法结果
*/ ** 调用accMul(arg1,arg2)
function digitLength (num) { ** 返回值arg1乘以 arg2的精确结果
// Get digit length of e **/
var eSplit = num.toString().split(/[eE]/); function accMul(arg1, arg2) {
var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
return len > 0 ? len : 0; try {
m += s1.split(".")[1].length;
} catch (e) {
} }
/** try {
* 把小数转成整数支持科学计数法如果是小数则放大成整数 m += s2.split(".")[1].length;
* @param {*number} num 输入数 } catch (e) {
*/
function float2Fixed (num) {
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
}
var dLen = digitLength(num);
return dLen > 0 ? num * Math.pow(10, dLen) : num;
} }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
}
/** // 给Number类型增加一个div方法,调用起来更加方便。
* 精确乘法 export function div(num, arg) {
*/ return accDivide(num, arg);
function times (num1, num2) {
var others = []; /**
for (var _i = 2; _i < arguments.length; _i++) { * Return digits length of a number
others[_i - 2] = arguments[_i]; * @param {*number} num Input number
} */
if (others.length > 0) { function digitLength(num) {
return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); // Get digit length of e
} const eSplit = num.toString().split(/[eE]/);
var num1Changed = float2Fixed(num1); const len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0));
var num2Changed = float2Fixed(num2); return len > 0 ? len : 0;
var baseNum = digitLength(num1) + digitLength(num2); }
var leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum); /**
* 把小数转成整数支持科学计数法如果是小数则放大成整数
* @param {*number} num 输入数
*/
function float2Fixed(num) {
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
} }
const dLen = digitLength(num);
return dLen > 0 ? num * Math.pow(10, dLen) : num;
}
/** /**
* 精确除法 * 精确乘法
*/ */
function accDivide (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 accDivide.apply(void 0, [accDivide(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);
var num2Changed = float2Fixed(num2);
return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
} }
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
const baseNum = digitLength(num1) + digitLength(num2);
const leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum);
} }
}); /**
* 精确除法
*/
function accDivide(num1, num2) {
const others = [];
for (let _i = 2; _i < arguments.length; _i++) {
others[_i - 2] = arguments[_i];
}
if (others.length > 0) {
return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1)));
}
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
}
}

224
src/core/func/string.js

@ -1,123 +1,121 @@
import {isString} from "../2.base";
/** /**
* 对字符串对象的扩展 * 判断字符串是否已指定的字符串开始
* @class String * @param str source字符串
* @param {String} startTag 指定的开始字符串
* @return {Boolean} 如果字符串以指定字符串开始则返回true否则返回false
*/ */
BI._.extend(BI, { export function startWith(str, startTag) {
str = str || "";
if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) {
return false;
}
return str.substring(0, startTag.length) == startTag;
}
/** /**
* 判断字符串是否已指定的字符串开始 * 判断字符串是否以指定的字符串结束
* @param str source字符串 * @param str source字符串
* @param {String} startTag 指定的开始字符串 * @param {String} endTag 指定的字符串
* @return {Boolean} 如果字符串以指定字符串开始则返回true否则返回false * @return {Boolean} 如果字符串以指定字符串结束则返回true否则返回false
*/ */
startWith: function (str, startTag) { export function endWith(str, endTag) {
str = str || ""; if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { return false;
return false; }
} return str.substring(str.length - endTag.length) == endTag;
return str.substr(0, startTag.length) == startTag; }
},
/**
* 判断字符串是否以指定的字符串结束
* @param str source字符串
* @param {String} endTag 指定的字符串
* @return {Boolean} 如果字符串以指定字符串结束则返回true否则返回false
*/
endWith: function (str, endTag) {
if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
return false;
}
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 += "?";
} }
// 如果以问号结尾,说明没有其他参数 // 如果以问号结尾,说明没有其他参数
if (BI.endWith(src, "?") !== false) { if (BI.endWith(src, "?") !== false) {
} else { } else {
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);
return src;
},
/**
* 将所有符合第一个字符串所表示的字符串替换成为第二个字符串
* @param str source字符串
* @param {String} s1 要替换的字符串的正则表达式
* @param {String} s2 替换的结果字符串
* @returns {String} 替换后的字符串
*/
replaceAll: function (str, s1, s2) {
return BI.isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str;
},
/**
* 总是让字符串以指定的字符开头
* @param str source字符串
* @param {String} start 指定的字符
* @returns {String} 以指定字符开头的字符串
*/
perfectStart: function (str, start) {
if (BI.startWith(str, start)) {
return str;
} }
return start + str; });
src = src.substr(0, src.length - 1);
return src;
}
}, /**
* 将所有符合第一个字符串所表示的字符串替换成为第二个字符串
* @param str source字符串
* @param {String} s1 要替换的字符串的正则表达式
* @param {String} s2 替换的结果字符串
* @returns {String} 替换后的字符串
*/
export function replaceAll(str, s1, s2) {
return isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str;
}
/** /**
* 获取字符串中某字符串的所有项位置数组 * 总是让字符串以指定的字符开头
* @param str source字符串 * @param str source字符串
* @param {String} sub 子字符串 * @param {String} start 指定的字符
* @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组 * @returns {String} 以指定字符开头的字符串
*/ */
allIndexOf: function (str, sub) { export function perfectStart(str, start) {
if (typeof sub !== "string") { if (BI.startWith(str, start)) {
return []; return str;
} }
var location = []; return start + str;
var offset = 0;
while (str.length > 0) { }
var loc = str.indexOf(sub);
if (loc === -1) { /**
break; * 获取字符串中某字符串的所有项位置数组
} * @param str source字符串
location.push(offset + loc); * @param {String} sub 子字符串
str = str.substring(loc + sub.length, str.length); * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组
offset += loc + sub.length; */
export function allIndexOf(str, sub) {
if (typeof sub !== "string") {
return [];
}
const location = [];
let offset = 0;
while (str.length > 0) {
const loc = str.indexOf(sub);
if (loc === -1) {
break;
} }
return location; location.push(offset + loc);
str = str.substring(loc + sub.length, str.length);
offset += loc + sub.length;
} }
}); 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
} };

123
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,64 +553,58 @@ 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 () {
element.__resizeListeners__.forEach(function (listener) { element.__resizeListeners__.forEach(function (listener) {
BI.$(element).is(":visible") && listener(); BI.$(element).is(":visible") && listener();
});
}); });
resizeObserver.observe(element); });
element.__resizeObserver__ = resizeObserver; resizeObserver.observe(element);
} element.__resizeObserver__ = resizeObserver;
if (!element.__resizeListeners__) {
element.__resizeListeners__ = [];
}
element.__resizeListeners__.push(fn);
} }
}; if (!element.__resizeListeners__) {
var removeResizeListener = function (element, fn) { element.__resizeListeners__ = [];
if (ResizeObserver) { }
if (BI.isNull(fn)) { element.__resizeListeners__.push(fn);
element.__resizeListeners__ = []; }
};
var removeResizeListener = function (element, fn) {
if (ResizeObserver) {
if (BI.isNull(fn)) {
element.__resizeListeners__ = [];
element.__resizeObserver__ && element.__resizeObserver__.unobserve(element);
element.__resizeObserver__ = null;
return;
}
var index = element.__resizeListeners__.indexOf(fn);
if (index >= 0) {
element.__resizeListeners__.splice(index, 1);
if (!element.__resizeListeners__.length) {
element.__resizeObserver__ && element.__resizeObserver__.unobserve(element); element.__resizeObserver__ && element.__resizeObserver__.unobserve(element);
element.__resizeObserver__ = null; element.__resizeObserver__ = null;
return;
}
var index = element.__resizeListeners__.indexOf(fn);
if (index >= 0) {
element.__resizeListeners__.splice(index, 1);
if (!element.__resizeListeners__.length) {
element.__resizeObserver__ && element.__resizeObserver__.unobserve(element);
element.__resizeObserver__ = null;
}
} }
} }
}; }
};
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 () {
removeResizeListener(widget.element[0], fn);
};
}, removeResizeListener: function (widget, fn) {
removeResizeListener(widget.element[0], fn); removeResizeListener(widget.element[0], fn);
} };
}; }, removeResizeListener: function (widget, fn) {
})(); removeResizeListener(widget.element[0], fn);
}
};
Object.assign(BI, {
ResizeDetector
});

863
src/core/utils/chinesePY.js

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