util.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /**
  2. * 工具类
  3. */
  4. import Config from "./config";
  5. const LOG_SHOW = Config.get('bluetoothConsole') //是否开启蓝牙调试
  6. /**
  7. * 对象转URL
  8. * @param {object} obj
  9. */
  10. export const urlEncode = (obj = {}) => {
  11. const result = []
  12. for (const key in obj) {
  13. const item = obj[key]
  14. if (!item) {
  15. continue
  16. }
  17. if (isArray(item)) {
  18. item.forEach(val => {
  19. result.push(key + '=' + val)
  20. })
  21. } else {
  22. result.push(key + '=' + item)
  23. }
  24. }
  25. return result.join('&')
  26. }
  27. /**
  28. * 遍历对象
  29. */
  30. export const objForEach = (obj, callback) => {
  31. Object.keys(obj).forEach((key) => {
  32. callback(obj[key], key)
  33. });
  34. }
  35. /**
  36. * 是否在数组内
  37. */
  38. export const inArray = (search, array) => {
  39. for (var i in array) {
  40. if (array[i] == search) return true
  41. }
  42. return false
  43. }
  44. /**
  45. * 判断是否为空对象
  46. * @param {*} object 源对象
  47. */
  48. export const isEmptyObject = (object) => {
  49. return Object.keys(object).length === 0
  50. }
  51. /**
  52. * 判断是否为对象
  53. * @param {*} object
  54. */
  55. export const isObject = (object) => {
  56. return Object.prototype.toString.call(object) === '[object Object]'
  57. }
  58. /**
  59. * 判断是否为数组
  60. * @param {*} array
  61. */
  62. export const isArray = (array) => {
  63. return Object.prototype.toString.call(array) === '[object Array]'
  64. }
  65. /**
  66. * 判断是否为空
  67. * @param {*} object 源对象
  68. */
  69. export const isEmpty = (value) => {
  70. if (isArray(value)) {
  71. return value.length === 0
  72. }
  73. if (isObject(value)) {
  74. return isEmptyObject(value)
  75. }
  76. return !value
  77. }
  78. /**
  79. * 对象深拷贝
  80. * @param {*} obj 源对象
  81. */
  82. export const cloneObj = (obj) => {
  83. let newObj = obj.constructor === Array ? [] : {};
  84. if (typeof obj !== 'object') {
  85. return;
  86. }
  87. for (let i in obj) {
  88. newObj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
  89. }
  90. return newObj
  91. }
  92. /**
  93. * 数组交集
  94. * @param {Array} 数组1
  95. * @param {Array} 数组2
  96. * @return {Array}
  97. */
  98. export const arrayIntersect = (array1, array2) => {
  99. return array1.filter(val => array2.indexOf(val) > -1)
  100. }
  101. export const arrayFindData = (data, value, keyName, itemName = null, label = 1) => {
  102. let info = [];
  103. let itemIsArray = false
  104. if (isEmpty(data)) return info
  105. if (data && isArray(data[0][keyName])) itemIsArray = true
  106. let valueIsArray = false
  107. if (isArray(value)) valueIsArray = true
  108. data.some((item, index) => {
  109. if (
  110. (!itemIsArray && !valueIsArray && value == item[keyName]) ||
  111. (itemIsArray && !valueIsArray && inArray(value, item[keyName])) ||
  112. (!itemIsArray && valueIsArray && inArray(item[keyName], value))
  113. ) {
  114. info.push({
  115. index: index,
  116. value: item
  117. })
  118. return info;
  119. } else if (label - 1 > 0 && item[itemName] instanceof Array) {
  120. let aaa = arrayFindData(item[itemName], value, keyName, itemName, label - 1)
  121. if (aaa.length > 0) {
  122. info.push({
  123. index: index,
  124. value: item
  125. })
  126. info.push(...aaa);
  127. return info;
  128. }
  129. }
  130. });
  131. return info;
  132. }
  133. export const array_column = (arr = [], column, indexKey = null) => {
  134. let data = {};
  135. if (column && indexKey) {
  136. arr.forEach((item) => {
  137. data[item[indexKey]] = item[column]
  138. })
  139. } else if (column && !indexKey) {
  140. data = []
  141. arr.forEach((item) => {
  142. data.push(item[column])
  143. })
  144. } else {
  145. arr.forEach((item) => {
  146. data[item[indexKey]] = item
  147. })
  148. }
  149. return data
  150. }
  151. export const secondsConvert = (seconds) => {
  152. if (!seconds) return '00:00'
  153. return formatZero(parseInt(seconds / 60), 2) + ':' + formatZero(seconds % 60, 2)
  154. }
  155. export const msConvert = (seconds) => {
  156. if (!seconds) return "00′00"
  157. return formatZero(parseInt(seconds / 1000), 2) + "′" + formatZero(seconds % 1000, 3)
  158. }
  159. /**
  160. * 数字不够x位,前面补0
  161. * @param {*} num 数字
  162. * @param {*} len 补零长度
  163. * @returns 0001
  164. */
  165. export function formatZero(num, len) {
  166. if (String(num).length > len) {
  167. return num;
  168. }
  169. return (Array(len).join(0) + num).slice(-len)
  170. }
  171. /**
  172. * 字符串按指定长度切割
  173. * @param str
  174. * @param size
  175. * @returns {*[]}
  176. */
  177. export function sliceChunk(str, size = 2) {
  178. const reg = new RegExp(`.{1,${size}}`, 'g');
  179. return str.match(reg);
  180. }
  181. export const sleep = (interval) => {
  182. return new Promise((resolve) => {
  183. setTimeout(resolve, interval);
  184. }
  185. )
  186. }
  187. /**
  188. * 对微信接口的promise封装
  189. * @param {function} fn
  190. * @param {object} args
  191. */
  192. export const promisify = (fn, args) => {
  193. return new Promise((resolve, reject) => {
  194. fn({
  195. ...(args || {}),
  196. success: (res) => resolve(res),
  197. fail: (err) => reject(err),
  198. });
  199. });
  200. }
  201. export const logs = (...arr) => {
  202. LOG_SHOW && console.info('调试打印', ...arr)
  203. }
  204. /**
  205. * 格式化数字
  206. * @param value
  207. * @param detault
  208. * @param maxLenght
  209. * @param decimalLength
  210. * @returns {number|string}
  211. */
  212. export const formatterConvert = (value, detault = '', maxLenght = 5, decimalLength = 0, isMinus = false) => {
  213. if (value[0] == '-') {
  214. value = value.slice(1)
  215. }
  216. value = value.toString()
  217. let result = value.split(".")
  218. if (value.charAt(value.length - 1) === '.' && decimalLength > 0) {
  219. let num = Math.abs(result[0])
  220. return num + '.' || detault
  221. }
  222. if (result.length > 2) result = result.slice(0, 2)
  223. if (result[0].length > maxLenght) {
  224. result[0] = result[0].slice(0, maxLenght)
  225. }
  226. if (result[0].length > 0) result[0] = Math.abs(result[0])
  227. if (decimalLength > 0) {
  228. if (result[1]) result[1] = result[1].slice(0, decimalLength)
  229. } else {
  230. if (result[1]) result = result.slice(1, 1)
  231. }
  232. let res = result.join('.') || detault
  233. return res
  234. }
  235. /**
  236. * 获取结果值在数组内容
  237. * @param data
  238. * @param value
  239. * @param keyName
  240. * @param itemName
  241. * @param label
  242. * @returns {Promise<*>}
  243. */
  244. export const findArrayInfo = async (data, value, keyName, itemName = null, label = 1) => {
  245. let info = await arrayFindData(data, value, keyName, itemName, label)
  246. return Promise.resolve(info);
  247. }
  248. /**
  249. * 获取结果值在数组中的下标
  250. * @param arr
  251. * @param val
  252. * @param itemName
  253. */
  254. export const findArrayIndex = async (arr, val, itemName) => {
  255. if (!arr.length) return -1;
  256. let resultIndex = arr.findIndex(function (value, index, arr) {
  257. let values = itemName ? value[itemName] : value;
  258. return values == val;
  259. })
  260. return resultIndex
  261. }
  262. export const array_chunk = (arr, size) => {
  263. let newArr = []
  264. for (let i = 0, len = arr.length; i < len; i += size) {
  265. newArr.push(arr.slice(i, i + size));
  266. }
  267. return newArr
  268. }
  269. export const arraySearchAndSort = async (list, keyword = '', keyName = 'name') => {
  270. list.forEach((item) => {
  271. item.arraySearchName = item[keyName]
  272. item.arraySearchKey = 0
  273. if (!keyword) return true
  274. let reg = item[keyName].match(RegExp(`${keyword}`));
  275. item.arraySearchKey = reg ? reg.length : 0
  276. if (item.arraySearchKey > 0) {
  277. item.arraySearchName = item.arraySearchName.replace(new RegExp(`(${keyword})`, 'g'), `${keyword}`)
  278. }
  279. })
  280. return list
  281. }
  282. export const strToObject = (str) => {
  283. let arr = str.split(";");
  284. let data = {}
  285. arr.forEach((item) => {
  286. if (!item) return true
  287. let itemArr = item.split(':')
  288. data[itemArr[0]] = itemArr[1]
  289. })
  290. return data
  291. }
  292. export const objectToStr = (arr) => {
  293. let data = []
  294. Object.keys(arr).forEach((item) => {
  295. data.push(`${item}:${arr[item]}`)
  296. })
  297. return data.join(';') + ';'
  298. }
  299. export const countdownTimer = (callback, duration = 5) => {
  300. let timer = setInterval(function () {
  301. duration--;
  302. if (duration < 0) {
  303. clearInterval(timer);
  304. }
  305. }, 1000);
  306. }
  307. /**
  308. *
  309. * */
  310. export const pxTorpx = (px) => {
  311. let deviceWidth = uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
  312. let rpx = (750 / deviceWidth) * Number(px)
  313. return Math.floor(rpx);
  314. }
  315. export const getAllMethods = (obj) => {
  316. let methods = new Set();
  317. let currentObj = obj;
  318. do {
  319. Object.getOwnPropertyNames(currentObj).forEach(prop => {
  320. if (typeof obj[prop] === 'function') {
  321. methods.add(prop);
  322. }
  323. });
  324. currentObj = Object.getPrototypeOf(currentObj);
  325. } while (currentObj && currentObj !== Object.prototype); // 避免添加Object的默认方法
  326. return Array.from(methods).filter(method => method !== 'constructor');
  327. }