utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { isDef, isNumber, isPlainObject, isPromise } from './validator';
  2. import { canIUseGroupSetData, canIUseNextTick, getSystemInfoSync, } from './version';
  3. export { isDef } from './validator';
  4. export { getSystemInfoSync } from './version';
  5. export function range(num, min, max) {
  6. return Math.min(Math.max(num, min), max);
  7. }
  8. export function nextTick(cb) {
  9. if (canIUseNextTick()) {
  10. wx.nextTick(cb);
  11. }
  12. else {
  13. setTimeout(() => {
  14. cb();
  15. }, 1000 / 30);
  16. }
  17. }
  18. export function addUnit(value) {
  19. if (!isDef(value)) {
  20. return undefined;
  21. }
  22. value = String(value);
  23. return isNumber(value) ? `${value}px` : value;
  24. }
  25. export function requestAnimationFrame(cb) {
  26. return setTimeout(() => {
  27. cb();
  28. }, 1000 / 30);
  29. }
  30. export function pickExclude(obj, keys) {
  31. if (!isPlainObject(obj)) {
  32. return {};
  33. }
  34. return Object.keys(obj).reduce((prev, key) => {
  35. if (!keys.includes(key)) {
  36. prev[key] = obj[key];
  37. }
  38. return prev;
  39. }, {});
  40. }
  41. export function getRect(context, selector) {
  42. return new Promise((resolve) => {
  43. wx.createSelectorQuery()
  44. .in(context)
  45. .select(selector)
  46. .boundingClientRect()
  47. .exec((rect = []) => resolve(rect[0]));
  48. });
  49. }
  50. export function getAllRect(context, selector) {
  51. return new Promise((resolve) => {
  52. wx.createSelectorQuery()
  53. .in(context)
  54. .selectAll(selector)
  55. .boundingClientRect()
  56. .exec((rect = []) => resolve(rect[0]));
  57. });
  58. }
  59. export function groupSetData(context, cb) {
  60. if (canIUseGroupSetData()) {
  61. context.groupSetData(cb);
  62. }
  63. else {
  64. cb();
  65. }
  66. }
  67. export function toPromise(promiseLike) {
  68. if (isPromise(promiseLike)) {
  69. return promiseLike;
  70. }
  71. return Promise.resolve(promiseLike);
  72. }
  73. // 浮点数精度处理
  74. export function addNumber(num1, num2) {
  75. const cardinal = Math.pow(10, 10);
  76. return Math.round((num1 + num2) * cardinal) / cardinal;
  77. }
  78. // 限制value在[min, max]之间
  79. export const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
  80. export function getCurrentPage() {
  81. const pages = getCurrentPages();
  82. return pages[pages.length - 1];
  83. }
  84. export const isPC = ['mac', 'windows'].includes(getSystemInfoSync().platform);