Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.46 KB | None | 0 0
  1. /**
  2. * Parse the time to string
  3. * @param {(Object|string|number)} time
  4. * @param {string} cFormat
  5. * @returns {string}
  6. */
  7. export function parseTime(time, cFormat) {
  8. if (arguments.length === 0) {
  9. return null
  10. }
  11.  
  12. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  13.  
  14. let date
  15. if (typeof time === 'object') {
  16. date = time
  17. } else {
  18. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  19. time = parseInt(time)
  20. }
  21. if ((typeof time === 'number') && (time.toString().length === 10)) {
  22. time = time * 1000
  23. }
  24. date = new Date(time)
  25. }
  26. const formatObj = {
  27. y: date.getFullYear(),
  28. m: date.getMonth() + 1,
  29. d: date.getDate(),
  30. h: date.getHours(),
  31. i: date.getMinutes(),
  32. s: date.getSeconds(),
  33. a: date.getDay()
  34. }
  35. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  36. let value = formatObj[key]
  37. // Note: getDay() returns 0 on Sunday
  38. if (key === 'a') {
  39. return ['日', '一', '二', '三', '四', '五', '六'][value]
  40. }
  41. if (result.length > 0 && value < 10) {
  42. value = '0' + value
  43. }
  44. return value || 0
  45. })
  46. return time_str
  47. }
  48.  
  49. /**
  50. * @param {number} time
  51. * @param {string} option
  52. * @returns {string}
  53. */
  54. export function formatTime(time, option) {
  55. if (('' + time).length === 10) {
  56. time = parseInt(time) * 1000
  57. } else {
  58. time = +time
  59. }
  60. const d = new Date(time)
  61. const now = Date.now()
  62.  
  63. const diff = (now - d) / 1000
  64.  
  65. if (diff < 30) {
  66. return '刚刚'
  67. } else if (diff < 3600) {
  68. // less 1 hour
  69. return Math.ceil(diff / 60) + '分钟前'
  70. } else if (diff < 3600 * 24) {
  71. return Math.ceil(diff / 3600) + '小时前'
  72. } else if (diff < 3600 * 24 * 2) {
  73. return '1天前'
  74. }
  75. if (option) {
  76. return parseTime(time, option)
  77. } else {
  78. return (
  79. d.getMonth() +
  80. 1 +
  81. '月' +
  82. d.getDate() +
  83. '日' +
  84. d.getHours() +
  85. '时' +
  86. d.getMinutes() +
  87. '分'
  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. /**
  112. * @param {string} input value
  113. * @returns {number} output value
  114. */
  115. export function byteLength(str) {
  116. // returns the byte length of an utf8 string
  117. let s = str.length
  118. for (var i = str.length - 1; i >= 0; i--) {
  119. const code = str.charCodeAt(i)
  120. if (code > 0x7f && code <= 0x7ff) s++
  121. else if (code > 0x7ff && code <= 0xffff) s += 2
  122. if (code >= 0xDC00 && code <= 0xDFFF) i--
  123. }
  124. return s
  125. }
  126.  
  127. /**
  128. * @param {Array} actual
  129. * @returns {Array}
  130. */
  131. export function cleanArray(actual) {
  132. const newArray = []
  133. for (let i = 0; i < actual.length; i++) {
  134. if (actual[i]) {
  135. newArray.push(actual[i])
  136. }
  137. }
  138. return newArray
  139. }
  140.  
  141. /**
  142. * @param {Object} json
  143. * @returns {Array}
  144. */
  145. export function param(json) {
  146. if (!json) return ''
  147. return cleanArray(
  148. Object.keys(json).map(key => {
  149. if (json[key] === undefined) return ''
  150. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  151. })
  152. ).join('&')
  153. }
  154.  
  155. /**
  156. * @param {string} url
  157. * @returns {Object}
  158. */
  159. export function param2Obj(url) {
  160. const search = url.split('?')[1]
  161. if (!search) {
  162. return {}
  163. }
  164. return JSON.parse(
  165. '{"' +
  166. decodeURIComponent(search)
  167. .replace(/"/g, '\\"')
  168. .replace(/&/g, '","')
  169. .replace(/=/g, '":"')
  170. .replace(/\+/g, ' ') +
  171. '"}'
  172. )
  173. }
  174.  
  175. /**
  176. * @param {string} val
  177. * @returns {string}
  178. */
  179. export function html2Text(val) {
  180. const div = document.createElement('div')
  181. div.innerHTML = val
  182. return div.textContent || div.innerText
  183. }
  184.  
  185. /**
  186. * Merges two objects, giving the last one precedence
  187. * @param {Object} target
  188. * @param {(Object|Array)} source
  189. * @returns {Object}
  190. */
  191. export function objectMerge(target, source) {
  192. if (typeof target !== 'object') {
  193. target = {}
  194. }
  195. if (Array.isArray(source)) {
  196. return source.slice()
  197. }
  198. Object.keys(source).forEach(property => {
  199. const sourceProperty = source[property]
  200. if (typeof sourceProperty === 'object') {
  201. target[property] = objectMerge(target[property], sourceProperty)
  202. } else {
  203. target[property] = sourceProperty
  204. }
  205. })
  206. return target
  207. }
  208.  
  209. /**
  210. * @param {HTMLElement} element
  211. * @param {string} className
  212. */
  213. export function toggleClass(element, className) {
  214. if (!element || !className) {
  215. return
  216. }
  217. let classString = element.className
  218. const nameIndex = classString.indexOf(className)
  219. if (nameIndex === -1) {
  220. classString += '' + className
  221. } else {
  222. classString =
  223. classString.substr(0, nameIndex) +
  224. classString.substr(nameIndex + className.length)
  225. }
  226. element.className = classString
  227. }
  228.  
  229. /**
  230. * @param {string} type
  231. * @returns {Date}
  232. */
  233. export function getTime(type) {
  234. if (type === 'start') {
  235. return new Date().getTime() - 3600 * 1000 * 24 * 90
  236. } else {
  237. return new Date(new Date().toDateString())
  238. }
  239. }
  240.  
  241. /**
  242. * @param {Function} func
  243. * @param {number} wait
  244. * @param {boolean} immediate
  245. * @return {*}
  246. */
  247. export function debounce(func, wait, immediate) {
  248. let timeout, args, context, timestamp, result
  249.  
  250. const later = function() {
  251. // 据上一次触发时间间隔
  252. const last = +new Date() - timestamp
  253.  
  254. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  255. if (last < wait && last > 0) {
  256. timeout = setTimeout(later, wait - last)
  257. } else {
  258. timeout = null
  259. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  260. if (!immediate) {
  261. result = func.apply(context, args)
  262. if (!timeout) context = args = null
  263. }
  264. }
  265. }
  266.  
  267. return function(...args) {
  268. context = this
  269. timestamp = +new Date()
  270. const callNow = immediate && !timeout
  271. // 如果延时不存在,重新设定延时
  272. if (!timeout) timeout = setTimeout(later, wait)
  273. if (callNow) {
  274. result = func.apply(context, args)
  275. context = args = null
  276. }
  277.  
  278. return result
  279. }
  280. }
  281.  
  282. /**
  283. * This is just a simple version of deep copy
  284. * Has a lot of edge cases bug
  285. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  286. * @param {Object} source
  287. * @returns {Object}
  288. */
  289. export function deepClone(source) {
  290. if (!source && typeof source !== 'object') {
  291. throw new Error('error arguments', 'deepClone')
  292. }
  293. const targetObj = source.constructor === Array ? [] : {}
  294. Object.keys(source).forEach(keys => {
  295. if (source[keys] && typeof source[keys] === 'object') {
  296. targetObj[keys] = deepClone(source[keys])
  297. } else {
  298. targetObj[keys] = source[keys]
  299. }
  300. })
  301. return targetObj
  302. }
  303.  
  304. /**
  305. * @param {Array} arr
  306. * @returns {Array}
  307. */
  308. export function uniqueArr(arr) {
  309. return Array.from(new Set(arr))
  310. }
  311.  
  312. /**
  313. * @returns {string}
  314. */
  315. export function createUniqueString() {
  316. const timestamp = +new Date() + ''
  317. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  318. return (+(randomNum + timestamp)).toString(32)
  319. }
  320.  
  321. /**
  322. * Check if an element has a class
  323. * @param {HTMLElement} elm
  324. * @param {string} cls
  325. * @returns {boolean}
  326. */
  327. export function hasClass(ele, cls) {
  328. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  329. }
  330.  
  331. /**
  332. * Add class to element
  333. * @param {HTMLElement} elm
  334. * @param {string} cls
  335. */
  336. export function addClass(ele, cls) {
  337. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  338. }
  339.  
  340. /**
  341. * Remove class from element
  342. * @param {HTMLElement} elm
  343. * @param {string} cls
  344. */
  345. export function removeClass(ele, cls) {
  346. if (hasClass(ele, cls)) {
  347. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  348. ele.className = ele.className.replace(reg, ' ')
  349. }
  350. }
  351.  
  352. export function windowWidth() {
  353. let winWidth = 0
  354. if (window.innerWidth) {
  355. winWidth = window.innerWidth
  356. } else if (document.body && document.body.clientWidth) {
  357. winWidth = document.body.clientWidth
  358. }
  359. return winWidth
  360. }
  361.  
  362. export function windowHeight() {
  363. let winHeight = 0
  364. if (window.innerHeight) {
  365. winHeight = window.innerHeight
  366. } else if (document.body && document.body.clientHeight) {
  367. winHeight = document.body.clientHeight
  368. }
  369. return winHeight
  370. }
  371.  
  372. export function guid() {
  373. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  374. const r = (Math.random() * 16) | 0
  375. const v = c === 'x' ? r : (r & 0x3) | 0x8
  376. return v.toString(16)
  377. })
  378. }
  379.  
  380. export function shuffle(arr) {
  381. for (var i = arr.length - 1; i >= 0; i--) {
  382. var randomIndex = Math.floor(Math.random() * (i + 1))
  383. var itemAtIndex = arr[randomIndex]
  384. arr[randomIndex] = arr[i]
  385. arr[i] = itemAtIndex
  386. }
  387. return arr
  388. }
  389.  
  390. export function bytesToSize(bytes) {
  391. if (bytes === 0) return '0 B'
  392. var k = 1024
  393. var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  394. var i = Math.floor(Math.log(bytes) / Math.log(k))
  395. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  396. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
  397. }
  398.  
  399. export function replaceAll(str, s1, s2) {
  400. return str.replace(new RegExp(s1, 'gm'), s2)
  401. }
  402.  
  403. /**
  404. * compareVersion('1.11.0', '1.9.9')
  405. // 1
  406. */
  407. export function compareVersion(v1, v2) {
  408. v1 = v1.split('.')
  409. v2 = v2.split('.')
  410. var len = Math.max(v1.length, v2.length)
  411.  
  412. while (v1.length < len) {
  413. v1.push('0')
  414. }
  415. while (v2.length < len) {
  416. v2.push('0')
  417. }
  418.  
  419. for (var i = 0; i < len; i++) {
  420. var num1 = parseInt(v1[i])
  421. var num2 = parseInt(v2[i])
  422.  
  423. if (num1 > num2) {
  424. return 1
  425. } else if (num1 < num2) {
  426. return -1
  427. }
  428. }
  429. return 0
  430. }
  431.  
  432. export function subStrWithTail(str, subLength, startIndex = 0, tail = '..') {
  433. return str == null || str.length === 0 ? '' : str.substr(startIndex, subLength) + ((str.length - startIndex <= subLength) ? '' : tail)
  434. }
  435.  
  436. /**
  437. * 检查两个String数组项内容是否一致
  438. * @param {*} arr1
  439. * @param {*} arr2
  440. */
  441. export function strArrEquals(arr1, arr2) {
  442. if (arr1 === null && arr2 === null) return true
  443. if ((arr1 === null && arr2 !== null) ||
  444. (arr1 !== null && arr2 === null)) return false
  445. if (arr1.length !== arr2.length) return false
  446.  
  447. return arr1.every((v) => {
  448. return arr2.includes(v)
  449. })
  450. }
  451.  
  452. /**
  453. * 比较两个对象是否相等
  454. * @param {*} x
  455. * @param {*} y
  456. */
  457. export function equals(x, y) {
  458. var f1 = x instanceof Object
  459. var f2 = y instanceof Object
  460. if (!f1 || !f2) {
  461. return x === y
  462. }
  463. if (Object.keys(x).length !== Object.keys(y).length) {
  464. return false
  465. }
  466. var newX = Object.keys(x)
  467. for (var p in newX) {
  468. p = newX[p]
  469. var a = x[p] instanceof Object
  470. var b = y[p] instanceof Object
  471. if (a && b) {
  472. const equal = equals(x[p], y[p])
  473. if (!equal) {
  474. return equal
  475. }
  476. } else if (x[p] !== y[p]) {
  477. return false
  478. }
  479. }
  480. return true
  481. }
  482.  
  483. /**
  484. * 首字母大写
  485. * @param {*} str
  486. */
  487. export function firstWordUpper(str) {
  488. return str.substring(0, 1).toUpperCase() + str.substring(1)
  489. }
  490.  
  491. export function text2Html(text) {
  492. return '<p>' + text.replace(/\n/g, '</p><p>') + '</p>'
  493. }
  494.  
  495. /**
  496. * 获取图片信息
  497. * @param {*} url
  498. */
  499. export function getImageInfo(url) {
  500. return new Promise((resolve, reject) => {
  501. const img = new Image()
  502. img.onload = function() {
  503. resolve({
  504. src: this.src,
  505. width: this.width,
  506. height: this.height
  507. })
  508. }
  509. img.onerror = function() {
  510. reject(new Error('加载失败'))
  511. }
  512. img.src = url
  513. })
  514. }
  515.  
  516. export function queryString() {
  517. const vars = []
  518. let hash = []
  519. var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
  520. for (var i = 0; i < hashes.length; i++) {
  521. hash = hashes[i].split('=')
  522. vars.push(hash[0])
  523. vars[hash[0]] = hash[1]
  524. }
  525. return vars
  526. }
  527.  
  528. export function cutString(str, len, suffix) {
  529. if (!str) return ''
  530. if (len <= 0) return ''
  531. if (!suffix) suffix = ''
  532. var templen = 0
  533. for (var i = 0; i < str.length; i++) {
  534. if (str.charCodeAt(i) > 255) {
  535. templen += 2
  536. } else {
  537. templen++
  538. }
  539. if (templen === len) {
  540. return str.substring(0, i + 1) + suffix
  541. } else if (templen > len) {
  542. return str.substring(0, i) + suffix
  543. }
  544. }
  545. return str
  546. }
  547.  
  548. export function sleep(delay) {
  549. var start = (new Date()).getTime()
  550. while ((new Date()).getTime() - start < delay) {
  551. continue
  552. }
  553. }
  554.  
  555. export function arraySort(arr, key, orderType) {
  556. const arr2 = deepClone(arr)
  557. arr2.sort((x, y) => {
  558. return orderType === 'desc' ? (x[key] - y[key]) : (y[key] - x[key])
  559. })
  560. console.log(arr2)
  561. return arr2
  562. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement