index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /**
  2. * Created by PanJiaChen on 16/11/18.
  3. */
  4. import {includes} from "core-js/internals/array-includes";
  5. /**
  6. * Parse the time to string
  7. * @param {(Object|string|number)} time
  8. * @param {string} cFormat
  9. * @returns {string | null}
  10. */
  11. export function parseTime(time, cFormat) {
  12. if (arguments.length === 0 || !time || parseInt(time) === 0) {
  13. return null
  14. }
  15. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  16. let date
  17. if (typeof time === 'object') {
  18. date = time
  19. } else {
  20. if ((typeof time === 'string')) {
  21. if ((/^[0-9]+$/.test(time))) {
  22. // support "1548221490638"
  23. time = parseInt(time)
  24. } else {
  25. // support safari
  26. // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
  27. time = time.replace(new RegExp(/-/gm), '/')
  28. }
  29. }
  30. if ((typeof time === 'number') && (time.toString().length === 10)) {
  31. time = time * 1000
  32. }
  33. date = new Date(time)
  34. }
  35. const formatObj = {
  36. y: date.getFullYear(),
  37. m: date.getMonth() + 1,
  38. d: date.getDate(),
  39. h: date.getHours(),
  40. i: date.getMinutes(),
  41. s: date.getSeconds(),
  42. a: date.getDay()
  43. }
  44. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  45. const value = formatObj[key]
  46. // Note: getDay() returns 0 on Sunday
  47. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  48. return value.toString().padStart(2, '0')
  49. })
  50. return time_str
  51. }
  52. /**
  53. * @param {number} time
  54. * @param {string} option
  55. * @returns {string}
  56. */
  57. export function formatTime(time, option) {
  58. if (('' + time).length === 10) {
  59. time = parseInt(time) * 1000
  60. } else {
  61. time = +time
  62. }
  63. const d = new Date(time)
  64. const now = Date.now()
  65. const diff = (now - d) / 1000
  66. if (diff < 30) {
  67. return '刚刚'
  68. } else if (diff < 3600) {
  69. // less 1 hour
  70. return Math.ceil(diff / 60) + '分钟前'
  71. } else if (diff < 3600 * 24) {
  72. return Math.ceil(diff / 3600) + '小时前'
  73. } else if (diff < 3600 * 24 * 2) {
  74. return '1天前'
  75. }
  76. if (option) {
  77. return parseTime(time, option)
  78. } else {
  79. return (
  80. d.getMonth() +
  81. 1 +
  82. '月' +
  83. d.getDate() +
  84. '日' +
  85. d.getHours() +
  86. '时' +
  87. d.getMinutes() +
  88. '分'
  89. )
  90. }
  91. }
  92. /**
  93. * @param {string} url
  94. * @returns {Object}
  95. */
  96. export function getQueryObject(url) {
  97. url = url == null ? window.location.href : url
  98. const search = url.substring(url.lastIndexOf('?') + 1)
  99. const obj = {}
  100. const reg = /([^?&=]+)=([^?&=]*)/g
  101. search.replace(reg, (rs, $1, $2) => {
  102. const name = decodeURIComponent($1)
  103. let val = decodeURIComponent($2)
  104. val = String(val)
  105. obj[name] = val
  106. return rs
  107. })
  108. return obj
  109. }
  110. /**
  111. * @param {string} input value
  112. * @returns {number} output value
  113. */
  114. export function byteLength(str) {
  115. // returns the byte length of an utf8 string
  116. let s = str.length
  117. for (var i = str.length - 1; i >= 0; i--) {
  118. const code = str.charCodeAt(i)
  119. if (code > 0x7f && code <= 0x7ff) s++
  120. else if (code > 0x7ff && code <= 0xffff) s += 2
  121. if (code >= 0xDC00 && code <= 0xDFFF) i--
  122. }
  123. return s
  124. }
  125. /**
  126. * @param {Array} actual
  127. * @returns {Array}
  128. */
  129. export function cleanArray(actual) {
  130. const newArray = []
  131. for (let i = 0; i < actual.length; i++) {
  132. if (actual[i]) {
  133. newArray.push(actual[i])
  134. }
  135. }
  136. return newArray
  137. }
  138. /**
  139. * @param {Object} json
  140. * @returns {Array}
  141. */
  142. export function param(json) {
  143. if (!json) return ''
  144. return cleanArray(
  145. Object.keys(json).map(key => {
  146. if (json[key] === undefined) return ''
  147. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  148. })
  149. ).join('&')
  150. }
  151. /**
  152. * @param {string} url
  153. * @returns {Object}
  154. */
  155. export function param2Obj(url) {
  156. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  157. if (!search) {
  158. return {}
  159. }
  160. const obj = {}
  161. const searchArr = search.split('&')
  162. searchArr.forEach(v => {
  163. const index = v.indexOf('=')
  164. if (index !== -1) {
  165. const name = v.substring(0, index)
  166. const val = v.substring(index + 1, v.length)
  167. obj[name] = val
  168. }
  169. })
  170. return obj
  171. }
  172. /**
  173. * @param {string} val
  174. * @returns {string}
  175. */
  176. export function html2Text(val) {
  177. const div = document.createElement('div')
  178. div.innerHTML = val
  179. return div.textContent || div.innerText
  180. }
  181. /**
  182. * Merges two objects, giving the last one precedence
  183. * @param {Object} target
  184. * @param {(Object|Array)} source
  185. * @returns {Object}
  186. */
  187. export function objectMerge(target, source) {
  188. if (typeof target !== 'object') {
  189. target = {}
  190. }
  191. if (Array.isArray(source)) {
  192. return source.slice()
  193. }
  194. Object.keys(source).forEach(property => {
  195. const sourceProperty = source[property]
  196. if (typeof sourceProperty === 'object') {
  197. target[property] = objectMerge(target[property], sourceProperty)
  198. } else {
  199. target[property] = sourceProperty
  200. }
  201. })
  202. return target
  203. }
  204. /**
  205. * @param {HTMLElement} element
  206. * @param {string} className
  207. */
  208. export function toggleClass(element, className) {
  209. if (!element || !className) {
  210. return
  211. }
  212. let classString = element.className
  213. const nameIndex = classString.indexOf(className)
  214. if (nameIndex === -1) {
  215. classString += '' + className
  216. } else {
  217. classString =
  218. classString.substr(0, nameIndex) +
  219. classString.substr(nameIndex + className.length)
  220. }
  221. element.className = classString
  222. }
  223. /**
  224. * @param {string} type
  225. * @returns {Date}
  226. */
  227. export function getTime(type) {
  228. if (type === 'start') {
  229. return new Date().getTime() - 3600 * 1000 * 24 * 90
  230. } else {
  231. return new Date(new Date().toDateString())
  232. }
  233. }
  234. /**
  235. * @param {Function} func
  236. * @param {number} wait
  237. * @param {boolean} immediate
  238. * @return {*}
  239. */
  240. export function debounce(func, wait, immediate) {
  241. let timeout, args, context, timestamp, result
  242. const later = function() {
  243. // 据上一次触发时间间隔
  244. const last = +new Date() - timestamp
  245. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  246. if (last < wait && last > 0) {
  247. timeout = setTimeout(later, wait - last)
  248. } else {
  249. timeout = null
  250. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  251. if (!immediate) {
  252. result = func.apply(context, args)
  253. if (!timeout) context = args = null
  254. }
  255. }
  256. }
  257. return function(...args) {
  258. context = this
  259. timestamp = +new Date()
  260. const callNow = immediate && !timeout
  261. // 如果延时不存在,重新设定延时
  262. if (!timeout) timeout = setTimeout(later, wait)
  263. if (callNow) {
  264. result = func.apply(context, args)
  265. context = args = null
  266. }
  267. return result
  268. }
  269. }
  270. /**
  271. * This is just a simple version of deep copy
  272. * Has a lot of edge cases bug
  273. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  274. * @param {Object} source
  275. * @returns {Object}
  276. */
  277. export function deepClone(source) {
  278. if (!source && typeof source !== 'object') {
  279. throw new Error('error arguments', 'deepClone')
  280. }
  281. const targetObj = source.constructor === Array ? [] : {}
  282. Object.keys(source).forEach(keys => {
  283. if (source[keys] && typeof source[keys] === 'object') {
  284. targetObj[keys] = deepClone(source[keys])
  285. } else {
  286. targetObj[keys] = source[keys]
  287. }
  288. })
  289. return targetObj
  290. }
  291. /**
  292. * @param {Array} arr
  293. * @returns {Array}
  294. */
  295. export function uniqueArr(arr) {
  296. return Array.from(new Set(arr))
  297. }
  298. /**
  299. * @returns {string}
  300. */
  301. export function createUniqueString() {
  302. const timestamp = +new Date() + ''
  303. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  304. return (+(randomNum + timestamp)).toString(32)
  305. }
  306. /**
  307. * Check if an element has a class
  308. * @param {HTMLElement} elm
  309. * @param {string} cls
  310. * @returns {boolean}
  311. */
  312. export function hasClass(ele, cls) {
  313. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  314. }
  315. /**
  316. * Add class to element
  317. * @param {HTMLElement} elm
  318. * @param {string} cls
  319. */
  320. export function addClass(ele, cls) {
  321. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  322. }
  323. /**
  324. * Remove class from element
  325. * @param {HTMLElement} elm
  326. * @param {string} cls
  327. */
  328. export function removeClass(ele, cls) {
  329. if (hasClass(ele, cls)) {
  330. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  331. ele.className = ele.className.replace(reg, ' ')
  332. }
  333. }
  334. /**
  335. * 查询操作系统
  336. * @returns {string}
  337. */
  338. export function getOperatingSystem() {
  339. try {
  340. //检测当前操作系统
  341. if (/(android|Android|ANDROID)/i.test(navigator.userAgent)) {
  342. //这是Android平台下浏览器
  343. return "Android";
  344. }
  345. if (/(iPhone|iPad|iPod|iOS|iphone|ipad|ipod|ios)/i.test(navigator.userAgent)) {
  346. //这是iOS平台下浏览器
  347. return "ios"
  348. }
  349. if (/win|windows|Win|Windows/i.test(navigator.userAgent)) {
  350. //这是Linux平台下浏览器
  351. return "windows"
  352. }
  353. if (/Linux/i.test(navigator.platform)) {
  354. //这是Linux操作系统平台
  355. return "linux"
  356. }
  357. } catch (e) {
  358. //可以看看e是什么玩意
  359. console.log(e);
  360. //返回未知
  361. return "unknow";
  362. }
  363. }
  364. /**
  365. * 获取媒介尺寸
  366. * @returns {string}
  367. */
  368. export function getMedia() {
  369. return ['Android', 'ios'].includes(getOperatingSystem()) ? 'small' : 'medium';
  370. }
  371. /**
  372. * 查询屏幕分辨率宽度
  373. * @returns {number}
  374. */
  375. export function getScreenWidth() {
  376. return window.screen.width
  377. }
  378. /**
  379. * 查询屏幕分辨率宽度
  380. * @returns {number}
  381. */
  382. export function getScreenHeight() {
  383. return window.screen.height
  384. }
  385. /**
  386. * 金额千分符
  387. * @param amount
  388. * @returns {string}
  389. */
  390. export function formatAmount(amount) {
  391. amount = parseFloat(amount)
  392. if (amount === 0.00) {
  393. return '0';
  394. }
  395. amount = String(amount);
  396. let left = amount.split('.')[0]
  397. let right = amount.split('.')[1]
  398. right = right ? '.' + right : ''
  399. let temp = left.split('').reverse().join('').match(/(\d{1,3})/g)
  400. return (Number(amount) < 0 ? '-' : '') + temp.join(',').split('').reverse().join('') + right
  401. }