a2bei4-utils 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -797,133 +797,222 @@ function randomDateInRange(date1, date2) {
797
797
  return new Date(v1 + Math.floor(Math.random() * (v2 - v1 + 1)));
798
798
  }
799
799
 
800
+ //#region 持续时间相关
801
+
802
+ /**
803
+ * 时间持续对象(完整版本,包含年月日时分秒毫秒)
804
+ * @typedef {Object} DurationObject
805
+ * @property {number} years - 年数
806
+ * @property {number} months - 月数(0-11)
807
+ * @property {number} days - 天数(0-29,取决于 monthDays)
808
+ * @property {number} hours - 小时数(0-23)
809
+ * @property {number} minutes - 分钟数(0-59)
810
+ * @property {number} seconds - 秒数(0-59)
811
+ * @property {number} milliseconds - 毫秒数(0-999)
812
+ */
813
+
800
814
  /**
801
- * 计算两个时间之间的剩余/已过时长(天-时-分-秒),返回带补零的展示对象。
815
+ * 时间持续对象(最大单位为天)
816
+ * @typedef {Object} DurationMaxDayObject
817
+ * @property {number} days - 天数
818
+ * @property {number} hours - 小时数(0-23)
819
+ * @property {number} minutes - 分钟数(0-59)
820
+ * @property {number} seconds - 秒数(0-59)
821
+ * @property {number} milliseconds - 毫秒数(0-999)
822
+ */
823
+
824
+ /**
825
+ * 时间持续对象(最大单位为小时)
826
+ * @typedef {Object} DurationMaxHourObject
827
+ * @property {number} hours - 小时数
828
+ * @property {number} minutes - 分钟数(0-59)
829
+ * @property {number} seconds - 秒数(0-59)
830
+ * @property {number} milliseconds - 毫秒数(0-999)
831
+ */
832
+
833
+ /**
834
+ * 将毫秒转换为时间持续对象。
802
835
  *
803
- * @param {string|number|Date} originalTime - 原始时间(可转 Date 的任意值)
804
- * @param {Date} [currentTime=new Date()] - 基准时间,默认当前
805
- * @returns {{days:number,hours:string,minutes:string,seconds:string}}
836
+ * @param {number} milliseconds - 毫秒数(非负整数)
837
+ * @param {Object} [options] - 选项对象。
838
+ * @param {number} [options.yearDays=365] - 一年的天数。
839
+ * @param {number} [options.monthDays=30] - 一月的天数。
840
+ * @returns {DurationObject} 时间持续对象
841
+ * @throws {TypeError} 当 milliseconds 不是有效数字
842
+ * @throws {RangeError} 当 milliseconds 为负数
843
+ * @throws {RangeError} 当 yearDays 或 monthDays 不是正整数
844
+ *
845
+ * @example
846
+ * // 基本用法
847
+ * millisecond2Duration(42070000500);
848
+ * // 返回: { years: 1, months: 4, days: 1, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
806
849
  */
807
- function calcTimeDifference(originalTime, currentTime = new Date()) {
808
- // 计算时间差(毫秒)
809
- const diffMs = currentTime - new Date(originalTime);
810
-
811
- // 转换为天、小时、分钟、秒
812
- const diffSeconds = Math.floor(diffMs / 1000);
813
- const days = Math.floor(diffSeconds / (3600 * 24));
814
- const hours = Math.floor((diffSeconds % (3600 * 24)) / 3600);
815
- const minutes = Math.floor((diffSeconds % 3600) / 60);
850
+ function millisecond2Duration(milliseconds, options = { yearDays: 365, monthDays: 30 }) {
851
+ // 参数验证
852
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
853
+ throw new TypeError("milliseconds must be a valid number");
854
+ }
855
+ if (milliseconds < 0) {
856
+ throw new RangeError("milliseconds must be a non-negative number");
857
+ }
858
+
859
+ // 默认选项
860
+ const { yearDays = 365, monthDays = 30 } = options;
861
+
862
+ // 选项验证
863
+ if (!Number.isInteger(yearDays) || yearDays <= 0) {
864
+ throw new RangeError("yearDays must be a positive integer");
865
+ }
866
+ if (!Number.isInteger(monthDays) || monthDays <= 0) {
867
+ throw new RangeError("monthDays must be a positive integer");
868
+ }
869
+
870
+ const totalMilliseconds = Math.floor(milliseconds);
871
+ const ms = totalMilliseconds % 1000;
872
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
873
+
816
874
  const seconds = diffSeconds % 60;
875
+ const minutes = Math.floor(diffSeconds / 60) % 60;
876
+ const hours = Math.floor(diffSeconds / 3600) % 24;
817
877
 
818
- const padZero = (num) => String(num).padStart(2, "0");
878
+ // 计算年、月、日
879
+ const totalDays = Math.floor(diffSeconds / 3600 / 24);
880
+ const years = Math.floor(totalDays / yearDays);
881
+ const remainingDays = totalDays % yearDays;
882
+ const months = Math.floor(remainingDays / monthDays);
883
+ const days = remainingDays % monthDays;
819
884
 
820
- return {
821
- days,
822
- hours: padZero(hours),
823
- minutes: padZero(minutes),
824
- seconds: padZero(seconds)
825
- };
885
+ return { years, months, days, hours, minutes, seconds, milliseconds: ms };
826
886
  }
827
887
 
828
888
  /**
829
- * 将总秒数格式化成人类可读的时间段文本。
830
- * 固定进制:1 年=365 天,1 月=30 天。
831
- *
832
- * @param {number} totalSeconds - 非负总秒数
833
- * @param {object} [options] - 格式化选项
834
- * @param {Partial<{year:string,month:string,day:string,hour:string,minute:string,second:string}>} [options.labels] - 各单位的自定义文本
835
- * @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.maxUnit] - 最大输出单位
836
- * @param {('year'|'month'|'day'|'hour'|'minute'|'second')} [options.minUnit] - 最小输出单位
837
- * @param {boolean} [options.showZero] - 是否强制显示 0 秒
838
- * @returns {string} 拼接后的时长文本,如“1天 02小时 30分钟”
839
- * @throws {TypeError} 当 totalSeconds 为非数字或负数时抛出
889
+ * 将毫秒转换为时间持续对象(最大单位为天)。
890
+ * @param {number} milliseconds - 毫秒数(非负整数)
891
+ * @returns {DurationMaxDayObject} 包含天、小时、分钟、秒、毫秒的时间持续对象
892
+ * @throws {TypeError} milliseconds 不是有效数字时抛出
893
+ * @throws {RangeError} milliseconds 为负数时抛出
894
+ * @example
895
+ * // 返回 { days: 486, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
896
+ * millisecond2DurationMaxDay(42070000500);
840
897
  */
841
- function formatDuration(totalSeconds, options = {}) {
842
- if (typeof totalSeconds !== "number" || totalSeconds < 0 || !isFinite(totalSeconds)) {
843
- throw new TypeError("totalSeconds 必须是非负数字");
898
+ function millisecond2DurationMaxDay(milliseconds) {
899
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
900
+ throw new TypeError("milliseconds must be a valid number");
901
+ }
902
+ if (milliseconds < 0) {
903
+ throw new RangeError("milliseconds must be a non-negative number");
844
904
  }
845
905
 
846
- // 1. 默认中文单位
847
- const DEFAULT_LABELS = {
848
- year: "年",
849
- month: "月",
850
- day: "天",
851
- hour: "小时",
852
- minute: "分钟",
853
- second: "秒"
854
- };
906
+ const totalMilliseconds = Math.floor(milliseconds);
907
+ const ms = totalMilliseconds % 1000;
908
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
855
909
 
856
- // 2. 固定进制表(秒)
857
- const UNIT_TABLE = [
858
- { key: "year", seconds: 365 * 24 * 3600 },
859
- { key: "month", seconds: 30 * 24 * 3600 },
860
- { key: "day", seconds: 24 * 3600 },
861
- { key: "hour", seconds: 3600 },
862
- { key: "minute", seconds: 60 },
863
- { key: "second", seconds: 1 }
864
- ];
865
-
866
- // 3. 合并用户自定义文本
867
- const labels = Object.assign({}, DEFAULT_LABELS, options.labels);
868
-
869
- // 4. 根据 maxUnit / minUnit 截取
870
- let start = 0,
871
- end = UNIT_TABLE.length;
872
- if (options.maxUnit) {
873
- const idx = UNIT_TABLE.findIndex((u) => u.key === options.maxUnit);
874
- if (idx !== -1) start = idx;
875
- }
876
- if (options.minUnit) {
877
- const idx = UNIT_TABLE.findIndex((u) => u.key === options.minUnit);
878
- if (idx !== -1) end = idx + 1;
879
- }
880
- const units = UNIT_TABLE.slice(start, end);
881
- if (!units.length) units.push(UNIT_TABLE[UNIT_TABLE.length - 1]); // 保底秒
882
-
883
- // 5. 逐级计算
884
- let rest = Math.floor(totalSeconds);
885
- const parts = [];
886
-
887
- for (const { key, seconds } of units) {
888
- const val = Math.floor(rest / seconds);
889
- rest %= seconds;
890
-
891
- const shouldShow = val > 0 || (options.showZero && key === "second");
892
- if (shouldShow || (parts.length === 0 && rest === 0)) {
893
- parts.push(`${val}${labels[key]}`);
894
- }
895
- }
910
+ const seconds = diffSeconds % 60;
911
+ const minutes = Math.floor(diffSeconds / 60) % 60;
912
+ const hours = Math.floor(diffSeconds / 3600) % 24;
913
+ const days = Math.floor(diffSeconds / 3600 / 24);
914
+
915
+ return { days, hours, minutes, seconds, milliseconds: ms };
916
+ }
896
917
 
897
- // 6. 兜底
898
- if (parts.length === 0) {
899
- parts.push(`0${labels[units[units.length - 1].key]}`);
918
+ /**
919
+ * 将毫秒转换为时间持续对象(最大单位为小时)。
920
+ * @param {number} milliseconds - 毫秒数(非负整数)
921
+ * @returns {DurationMaxHourObject} 包含小时、分钟、秒、毫秒的时间持续对象
922
+ * @throws {TypeError} 当 milliseconds 不是有效数字时抛出
923
+ * @throws {RangeError} 当 milliseconds 为负数时抛出
924
+ * @example
925
+ * // 返回 { hours: 11686, minutes: 6, seconds: 40, milliseconds: 500 }
926
+ * millisecond2DurationMaxHour(42070000500);
927
+ */
928
+ function millisecond2DurationMaxHour(milliseconds) {
929
+ if (typeof milliseconds !== "number" || isNaN(milliseconds)) {
930
+ throw new TypeError("milliseconds must be a valid number");
900
931
  }
932
+ if (milliseconds < 0) {
933
+ throw new RangeError("milliseconds must be a non-negative number");
934
+ }
935
+
936
+ const totalMilliseconds = Math.floor(milliseconds);
937
+ const ms = totalMilliseconds % 1000;
938
+ const diffSeconds = Math.floor(totalMilliseconds / 1000);
901
939
 
902
- return parts.join("");
940
+ const seconds = diffSeconds % 60;
941
+ const minutes = Math.floor(diffSeconds / 60) % 60;
942
+ const hours = Math.floor(diffSeconds / 3600);
943
+
944
+ return { hours, minutes, seconds, milliseconds: ms };
903
945
  }
904
946
 
905
947
  /**
906
- * 快捷调用 {@link formatDuration},最大单位到“天”。
948
+ * 将秒转换为时间持续对象。
907
949
  *
908
- * @param {number} totalSeconds
909
- * @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
910
- * @returns {string}
950
+ * @param {number} seconds - 秒数(非负整数)
951
+ * @param {Object} [options] - 选项对象。
952
+ * @param {number} [options.yearDays=365] - 一年的天数。
953
+ * @param {number} [options.monthDays=30] - 一月的天数。
954
+ * @returns {DurationObject} 时间持续对象
955
+ * @throws {TypeError} 当 seconds 不是有效数字
956
+ * @throws {RangeError} 当 seconds 为负数
957
+ * @throws {RangeError} 当 yearDays 或 monthDays 不是正整数
958
+ *
959
+ * @example
960
+ * // 基本用法
961
+ * second2Duration(42070000.5);
962
+ * // 返回: { years: 1, months: 4, days: 1, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
911
963
  */
912
- function formatDurationMaxDay(totalSeconds, options = {}) {
913
- return formatDuration(totalSeconds, { ...options, maxUnit: "day" });
964
+ function second2Duration(seconds, options = { yearDays: 365, monthDays: 30 }) {
965
+ if (typeof seconds !== "number" || isNaN(seconds)) {
966
+ throw new TypeError("seconds must be a valid number");
967
+ }
968
+ if (seconds < 0) {
969
+ throw new RangeError("seconds must be a non-negative number");
970
+ }
971
+ return millisecond2Duration(seconds * 1000, options);
914
972
  }
915
973
 
916
974
  /**
917
- * 快捷调用 {@link formatDuration},最大单位到“小时”。
918
- *
919
- * @param {number} totalSeconds
920
- * @param {Omit<Parameters<typeof formatDuration>[1],'maxUnit'>} [options]
921
- * @returns {string}
975
+ * 将秒转换为时间持续对象(最大单位为天)。
976
+ * @param {number} seconds - 秒数(非负整数)
977
+ * @returns {DurationMaxDayObject} 包含天、小时、分钟、秒、毫秒的时间持续对象
978
+ * @throws {TypeError} 当 seconds 不是有效数字时抛出
979
+ * @throws {RangeError} 当 seconds 为负数时抛出
980
+ * @example
981
+ * // 返回 { days: 486, hours: 22, minutes: 6, seconds: 40, milliseconds: 500 }
982
+ * second2DurationMaxDay(42070000.5);
983
+ */
984
+ function second2DurationMaxDay(seconds) {
985
+ if (typeof seconds !== "number" || isNaN(seconds)) {
986
+ throw new TypeError("seconds must be a valid number");
987
+ }
988
+ if (seconds < 0) {
989
+ throw new RangeError("seconds must be a non-negative number");
990
+ }
991
+ return millisecond2DurationMaxDay(seconds * 1000);
992
+ }
993
+
994
+ /**
995
+ * 将秒转换为时间持续对象(最大单位为小时)。
996
+ * @param {number} seconds - 秒数(非负整数)
997
+ * @returns {DurationMaxHourObject} 包含小时、分钟、秒、毫秒的时间持续对象
998
+ * @throws {TypeError} 当 seconds 不是有效数字时抛出
999
+ * @throws {RangeError} 当 seconds 为负数时抛出
1000
+ * @example
1001
+ * // 返回 { hours: 11686, minutes: 6, seconds: 40, milliseconds: 500 }
1002
+ * second2DurationMaxHour(42070000.5);
922
1003
  */
923
- function formatDurationMaxHour(totalSeconds, options = {}) {
924
- return formatDuration(totalSeconds, { ...options, maxUnit: "hour" });
1004
+ function second2DurationMaxHour(seconds) {
1005
+ if (typeof seconds !== "number" || isNaN(seconds)) {
1006
+ throw new TypeError("seconds must be a valid number");
1007
+ }
1008
+ if (seconds < 0) {
1009
+ throw new RangeError("seconds must be a non-negative number");
1010
+ }
1011
+ return millisecond2DurationMaxHour(seconds * 1000);
925
1012
  }
926
1013
 
1014
+ //#endregion
1015
+
927
1016
  /**
928
1017
  * 根据小时数返回对应的时间段名称。
929
1018
  *
@@ -2003,5 +2092,5 @@ class WebSocketManager {
2003
2092
  }
2004
2093
  }
2005
2094
 
2006
- export { AudioStreamResampler, IntervalTimer, MyEvent, MyEvent_CrossPagePlugin, MyId, WebSocketManager, assignExisting, calcTimeDifference, debounce, deepCloneByJSON, downloadByBlob, downloadByData, downloadByUrl, downloadExcel, downloadJSON, extractFullyCheckedKeys, fetchOrDownloadByUrl, findObjAttrValueById, flatCompleteTree2NestedTree, formatDuration, formatDurationMaxDay, formatDurationMaxHour, formatTimeForLocale, getAllSearchParams, getDataType, getFunctionArgNames, getGUID, getSearchParam, getTimePeriodName, getViewportSize, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, moveItem, nestedTree2IdMap, pcmToWavBlob, randomDateInRange, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, shuffle, throttle, toDate };
2095
+ export { AudioStreamResampler, IntervalTimer, MyEvent, MyEvent_CrossPagePlugin, MyId, WebSocketManager, assignExisting, debounce, deepCloneByJSON, downloadByBlob, downloadByData, downloadByUrl, downloadExcel, downloadJSON, extractFullyCheckedKeys, fetchOrDownloadByUrl, findObjAttrValueById, flatCompleteTree2NestedTree, formatTimeForLocale, getAllSearchParams, getDataType, getFunctionArgNames, getGUID, getSearchParam, getTimePeriodName, getViewportSize, isBlob, isDate, isFunction, isNonEmptyString, isPlainObject, isPromise, millisecond2Duration, millisecond2DurationMaxDay, millisecond2DurationMaxHour, moveItem, nestedTree2IdMap, pcmToWavBlob, randomDateInRange, randomEnLetter, randomHan, randomHanOrEn, randomIntInRange, readBlobAsText, second2Duration, second2DurationMaxDay, second2DurationMaxHour, shuffle, throttle, toDate };
2007
2096
  //# sourceMappingURL=a2bei4.utils.esm.js.map