util.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 long
  175. * @returns {*[]}
  176. */
  177. export function sliceChunk(str, long = 2) {
  178. let arr = [];
  179. for (let i = 0; i < str.length;) {
  180. arr.push(str.slice(i, i + long))
  181. i += long
  182. }
  183. return arr
  184. }
  185. export const sleep = (interval) => {
  186. return new Promise((resolve) => {
  187. setTimeout(resolve, interval);
  188. }
  189. )
  190. }
  191. /**
  192. * 对微信接口的promise封装
  193. * @param {function} fn
  194. * @param {object} args
  195. */
  196. export const promisify = (fn, args) => {
  197. return new Promise((resolve, reject) => {
  198. fn({
  199. ...(args || {}),
  200. success: (res) => resolve(res),
  201. fail: (err) => reject(err),
  202. });
  203. });
  204. }
  205. export const logs = (...arr) => {
  206. LOG_SHOW && console.info('调试打印', ...arr)
  207. }
  208. /**
  209. * 格式化数字
  210. * @param value
  211. * @param detault
  212. * @param maxLenght
  213. * @param decimalLength
  214. * @returns {number|string}
  215. */
  216. export const formatterConvert = (value, detault = '', maxLenght = 5, decimalLength = 0, isMinus = false) => {
  217. if (value[0] == '-') {
  218. value = value.slice(1)
  219. }
  220. value = value.toString()
  221. let result = value.split(".")
  222. if (value.charAt(value.length - 1) === '.' && decimalLength > 0) {
  223. let num = Math.abs(result[0])
  224. return num + '.' || detault
  225. }
  226. if (result.length > 2) result = result.slice(0, 2)
  227. if (result[0].length > maxLenght) {
  228. result[0] = result[0].slice(0, maxLenght)
  229. }
  230. if (result[0].length > 0) result[0] = Math.abs(result[0])
  231. if (decimalLength > 0) {
  232. if (result[1]) result[1] = result[1].slice(0, decimalLength)
  233. } else {
  234. if (result[1]) result = result.slice(1, 1)
  235. }
  236. let res = result.join('.') || detault
  237. return res
  238. }
  239. /**
  240. * 获取结果值在数组内容
  241. * @param data
  242. * @param value
  243. * @param keyName
  244. * @param itemName
  245. * @param label
  246. * @returns {Promise<*>}
  247. */
  248. export const findArrayInfo = async (data, value, keyName, itemName = null, label = 1) => {
  249. let info = await arrayFindData(data, value, keyName, itemName, label)
  250. return Promise.resolve(info);
  251. }
  252. /**
  253. * 获取结果值在数组中的下标
  254. * @param arr
  255. * @param val
  256. * @param itemName
  257. */
  258. export const findArrayIndex = async (arr, val, itemName) => {
  259. if (!arr.length) return -1;
  260. let resultIndex = arr.findIndex(function (value, index, arr) {
  261. let values = itemName ? value[itemName] : value;
  262. return values == val;
  263. })
  264. return resultIndex
  265. }
  266. export const array_chunk = (arr, size) => {
  267. let newArr = []
  268. for (let i = 0, len = arr.length; i < len; i += size) {
  269. newArr.push(arr.slice(i, i + size));
  270. }
  271. return newArr
  272. }
  273. export const arraySearchAndSort = async (list, keyword = '', keyName = 'name') => {
  274. list.forEach((item) => {
  275. item.arraySearchName = item[keyName]
  276. item.arraySearchKey = 0
  277. if (!keyword) return true
  278. let reg = item[keyName].match(RegExp(`${keyword}`));
  279. item.arraySearchKey = reg ? reg.length : 0
  280. if (item.arraySearchKey > 0) {
  281. item.arraySearchName = item.arraySearchName.replace(new RegExp(`(${keyword})`, 'g'), `${keyword}`)
  282. }
  283. })
  284. return list
  285. }
  286. export const strToObject = (str) => {
  287. let arr = str.split(";");
  288. let data = {}
  289. arr.forEach((item) => {
  290. if (!item) return true
  291. let itemArr = item.split(':')
  292. data[itemArr[0]] = itemArr[1]
  293. })
  294. return data
  295. }
  296. export const objectToStr = (arr) => {
  297. let data = []
  298. Object.keys(arr).forEach((item) => {
  299. data.push(`${item}:${arr[item]}`)
  300. })
  301. return data.join(';') + ';'
  302. }
  303. export const countdownTimer = (callback, duration = 5) => {
  304. let timer = setInterval(function () {
  305. duration--;
  306. if (duration < 0) {
  307. clearInterval(timer);
  308. }
  309. }, 1000);
  310. }
  311. /**
  312. *
  313. * */
  314. export const pxTorpx = (px) => {
  315. let deviceWidth = uni.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
  316. let rpx = (750 / deviceWidth) * Number(px)
  317. return Math.floor(rpx);
  318. }