index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /**
  2. * Created by PanJiaChen on 16/11/18.
  3. */
  4. /**
  5. * Parse the time to string
  6. * @param {(Object|string|number)} time
  7. * @param {string} cFormat
  8. * @returns {string | null}
  9. */
  10. export function parseTime(time, cFormat) {
  11. if (arguments.length === 0) {
  12. return null
  13. }
  14. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  15. let date
  16. if (typeof time === 'object') {
  17. date = time
  18. } else {
  19. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  20. time = parseInt(time)
  21. }
  22. if ((typeof time === 'number') && (time.toString().length === 10)) {
  23. time = time * 1000
  24. }
  25. date = new Date(time)
  26. }
  27. const formatObj = {
  28. y: date.getFullYear(),
  29. m: date.getMonth() + 1,
  30. d: date.getDate(),
  31. h: date.getHours(),
  32. i: date.getMinutes(),
  33. s: date.getSeconds(),
  34. a: date.getDay()
  35. }
  36. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  37. const value = formatObj[key]
  38. // Note: getDay() returns 0 on Sunday
  39. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
  40. return value.toString().padStart(2, '0')
  41. })
  42. return time_str
  43. }
  44. /**
  45. * @param {number} time
  46. * @param {string} option
  47. * @returns {string}
  48. */
  49. export function formatTime(time, option) {
  50. if (('' + time).length === 10) {
  51. time = parseInt(time) * 1000
  52. } else {
  53. time = +time
  54. }
  55. const d = new Date(time)
  56. const now = Date.now()
  57. const diff = (now - d) / 1000
  58. if (diff < 30) {
  59. return '刚刚'
  60. } else if (diff < 3600) {
  61. // less 1 hour
  62. return Math.ceil(diff / 60) + '分钟前'
  63. } else if (diff < 3600 * 24) {
  64. return Math.ceil(diff / 3600) + '小时前'
  65. } else if (diff < 3600 * 24 * 2) {
  66. return '1天前'
  67. }
  68. if (option) {
  69. return parseTime(time, option)
  70. } else {
  71. return (
  72. d.getMonth() +
  73. 1 +
  74. '月' +
  75. d.getDate() +
  76. '日' +
  77. d.getHours() +
  78. '时' +
  79. d.getMinutes() +
  80. '分'
  81. )
  82. }
  83. }
  84. /**
  85. * @param {string} url
  86. * @returns {Object}
  87. */
  88. export function getQueryObject(url) {
  89. url = url == null ? window.location.href : url
  90. const search = url.substring(url.lastIndexOf('?') + 1)
  91. const obj = {}
  92. const reg = /([^?&=]+)=([^?&=]*)/g
  93. search.replace(reg, (rs, $1, $2) => {
  94. const name = decodeURIComponent($1)
  95. let val = decodeURIComponent($2)
  96. val = String(val)
  97. obj[name] = val
  98. return rs
  99. })
  100. return obj
  101. }
  102. /**
  103. * @param {string} input value
  104. * @returns {number} output value
  105. */
  106. export function byteLength(str) {
  107. // returns the byte length of an utf8 string
  108. let s = str.length
  109. for (var i = str.length - 1; i >= 0; i--) {
  110. const code = str.charCodeAt(i)
  111. if (code > 0x7f && code <= 0x7ff) s++
  112. else if (code > 0x7ff && code <= 0xffff) s += 2
  113. if (code >= 0xDC00 && code <= 0xDFFF) i--
  114. }
  115. return s
  116. }
  117. /**
  118. * @param {Array} actual
  119. * @returns {Array}
  120. */
  121. export function cleanArray(actual) {
  122. const newArray = []
  123. for (let i = 0; i < actual.length; i++) {
  124. if (actual[i]) {
  125. newArray.push(actual[i])
  126. }
  127. }
  128. return newArray
  129. }
  130. /**
  131. * @param {Object} json
  132. * @returns {Array}
  133. */
  134. export function param(json) {
  135. if (!json) return ''
  136. return cleanArray(
  137. Object.keys(json).map(key => {
  138. if (json[key] === undefined) return ''
  139. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  140. })
  141. ).join('&')
  142. }
  143. /**
  144. * @param {string} url
  145. * @returns {Object}
  146. */
  147. export function param2Obj(url) {
  148. const search = url.split('?')[1]
  149. if (!search) {
  150. return {}
  151. }
  152. return JSON.parse(
  153. '{"' +
  154. decodeURIComponent(search)
  155. .replace(/"/g, '\\"')
  156. .replace(/&/g, '","')
  157. .replace(/=/g, '":"')
  158. .replace(/\+/g, ' ') +
  159. '"}'
  160. )
  161. }
  162. /**
  163. * @param {string} val
  164. * @returns {string}
  165. */
  166. export function html2Text(val) {
  167. const div = document.createElement('div')
  168. div.innerHTML = val
  169. return div.textContent || div.innerText
  170. }
  171. /**
  172. * Merges two objects, giving the last one precedence
  173. * @param {Object} target
  174. * @param {(Object|Array)} source
  175. * @returns {Object}
  176. */
  177. export function objectMerge(target, source) {
  178. if (typeof target !== 'object') {
  179. target = {}
  180. }
  181. if (Array.isArray(source)) {
  182. return source.slice()
  183. }
  184. Object.keys(source).forEach(property => {
  185. const sourceProperty = source[property]
  186. if (typeof sourceProperty === 'object') {
  187. target[property] = objectMerge(target[property], sourceProperty)
  188. } else {
  189. target[property] = sourceProperty
  190. }
  191. })
  192. return target
  193. }
  194. /**
  195. * @param {HTMLElement} element
  196. * @param {string} className
  197. */
  198. export function toggleClass(element, className) {
  199. if (!element || !className) {
  200. return
  201. }
  202. let classString = element.className
  203. const nameIndex = classString.indexOf(className)
  204. if (nameIndex === -1) {
  205. classString += '' + className
  206. } else {
  207. classString =
  208. classString.substr(0, nameIndex) +
  209. classString.substr(nameIndex + className.length)
  210. }
  211. element.className = classString
  212. }
  213. /**
  214. * @param {string} type
  215. * @returns {Date}
  216. */
  217. export function getTime(type) {
  218. if (type === 'start') {
  219. return new Date().getTime() - 3600 * 1000 * 24 * 90
  220. } else {
  221. return new Date(new Date().toDateString())
  222. }
  223. }
  224. /**
  225. * @param {Function} func
  226. * @param {number} wait
  227. * @param {boolean} immediate
  228. * @return {*}
  229. */
  230. export function debounce(func, wait, immediate) {
  231. let timeout, args, context, timestamp, result
  232. const later = function() {
  233. // 据上一次触发时间间隔
  234. const last = +new Date() - timestamp
  235. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  236. if (last < wait && last > 0) {
  237. timeout = setTimeout(later, wait - last)
  238. } else {
  239. timeout = null
  240. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  241. if (!immediate) {
  242. result = func.apply(context, args)
  243. if (!timeout) context = args = null
  244. }
  245. }
  246. }
  247. return function(...args) {
  248. context = this
  249. timestamp = +new Date()
  250. const callNow = immediate && !timeout
  251. // 如果延时不存在,重新设定延时
  252. if (!timeout) timeout = setTimeout(later, wait)
  253. if (callNow) {
  254. result = func.apply(context, args)
  255. context = args = null
  256. }
  257. return result
  258. }
  259. }
  260. /**
  261. * This is just a simple version of deep copy
  262. * Has a lot of edge cases bug
  263. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  264. * @param {Object} source
  265. * @returns {Object}
  266. */
  267. export function deepClone(source) {
  268. if (!source && typeof source !== 'object') {
  269. throw new Error('error arguments', 'deepClone')
  270. }
  271. const targetObj = source.constructor === Array ? [] : {}
  272. Object.keys(source).forEach(keys => {
  273. if (source[keys] && typeof source[keys] === 'object') {
  274. targetObj[keys] = deepClone(source[keys])
  275. } else {
  276. targetObj[keys] = source[keys]
  277. }
  278. })
  279. return targetObj
  280. }
  281. /**
  282. * @param {Array} arr
  283. * @returns {Array}
  284. */
  285. export function uniqueArr(arr) {
  286. return Array.from(new Set(arr))
  287. }
  288. /**
  289. * @returns {string}
  290. */
  291. export function createUniqueString() {
  292. const timestamp = +new Date() + ''
  293. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  294. return (+(randomNum + timestamp)).toString(32)
  295. }
  296. /**
  297. * Check if an element has a class
  298. * @param {HTMLElement} elm
  299. * @param {string} cls
  300. * @returns {boolean}
  301. */
  302. export function hasClass(ele, cls) {
  303. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  304. }
  305. /**
  306. * Add class to element
  307. * @param {HTMLElement} elm
  308. * @param {string} cls
  309. */
  310. export function addClass(ele, cls) {
  311. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  312. }
  313. /**
  314. * Remove class from element
  315. * @param {HTMLElement} elm
  316. * @param {string} cls
  317. */
  318. export function removeClass(ele, cls) {
  319. if (hasClass(ele, cls)) {
  320. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  321. ele.className = ele.className.replace(reg, ' ')
  322. }
  323. }
  324. /*
  325. * 解析地址栏参数
  326. *
  327. * @method getQueryObj
  328. *
  329. * @param
  330. *
  331. * @return {Object} 返回query参数对象
  332. *
  333. * */
  334. export function getQueryObj () {
  335. let href = window.location.href
  336. let query = href.substr(href.indexOf('?') + 1)
  337. let arr = query.split('&')
  338. let queryObj = {}
  339. for (let i = 0; i < arr.length; i++) {
  340. let keyVal = arr[i].split('=')
  341. queryObj[keyVal[0]] = keyVal[1]
  342. }
  343. return queryObj
  344. }
  345. /*
  346. * String过长,中间显示点
  347. *
  348. * @method interceptString
  349. *
  350. * @param {String} 目标字符串
  351. * @param {Number} 目标长度后开始截取,否则返回原String
  352. * @param {Number} String开始保留长度 1开始
  353. * @param {Number} String结尾保留长度
  354. *
  355. * @return {String} xxx...xxx 或 xxx
  356. * */
  357. export function interceptString (str, len, m, n) {
  358. if ((typeof str === 'string') && (typeof len === 'number') &&
  359. (typeof m === 'number') && (typeof n === 'number')) {
  360. if (len <= m + n) {
  361. throw new Error('长度参数有误,开始截取长度必须大于前后保留长度的和')
  362. }
  363. if (str.length > len) {
  364. return str.substring(0, m) + '...' + str.substring(str.length - n)
  365. } else {
  366. return str
  367. }
  368. } else {
  369. throw new Error('interceptString方法,参数类型错误')
  370. }
  371. }
  372. /*
  373. * 动态检测浏览器大小
  374. * @method windowWidth
  375. *
  376. * @return {Object} 浏览器宽度
  377. * */
  378. export function windowWH () {
  379. return {
  380. screenWidth: window.screen.width, // 屏幕分辨率,宽
  381. screenHeight: window.screen.height, // 屏幕分辨率,高
  382. screenAvailWidth: window.screen.availWidth, // 屏幕可用大小
  383. screenAvailHeight: window.screen.availHeight, // 屏幕可用大小
  384. clientWidth: document.body.clientWidth, // 网页可见区域宽
  385. clientHeight: document.body.clientHeight, // 网页可见区域高
  386. offsetWidth: document.body.offsetWidth, // 网页可见区域宽(包括边线的宽)
  387. offsetHeight: document.body.offsetHeight, // 网页可见区域高(包括边线的宽)
  388. scrollWidth: document.body.scrollWidth, // 网页正文全文宽
  389. scrollHeight: document.body.scrollHeight, // 网页正文全文高
  390. scrollTop: document.body.scrollTop, // 网页被卷去的高
  391. scrollLeft: document.body.scrollLeft, // 网页被卷去的左
  392. WinScreenTop: window.screenTop, // 网页正文部分左
  393. WinScrollLeft: window.screenLeft,
  394. }
  395. }
  396. /*
  397. * 对象深拷贝
  398. * @method deepCopy
  399. * @param p {Object} 拷贝对象
  400. * @param c {Object} 可选,拷贝到c对象
  401. * @return {Object} 拷贝对象
  402. * */
  403. export function deepCopy (source) {
  404. let result = {}
  405. for (let key in source) {
  406. result[key] = typeof source[key] === 'object'
  407. ? deepCopy(source[key])
  408. : source[key]
  409. }
  410. return result
  411. }
  412. export function deepCopyJson (p) {
  413. return JSON.parse((JSON.stringify(p)))
  414. }
  415. /*
  416. * 判断为数组
  417. * @method isArray
  418. * @param o {all} 判断的对象
  419. * @return {Boolean} 是否为数组
  420. * */
  421. export function isArray (o) {
  422. return Object.prototype.toString.call(o) === '[object Array]'
  423. }
  424. export function isArray2 (arr) {
  425. return arr instanceof Array
  426. }
  427. /*
  428. * 判断对象
  429. * @method isJsonObj
  430. * @param o {all} 判断的对象
  431. * @return {Boolean} 是否为对象
  432. * */
  433. export function isJsonObj (o) {
  434. if (o instanceof Object) {
  435. return o instanceof Array ? false : true // eslint-disable-line
  436. } else {
  437. return false
  438. }
  439. }
  440. export function arrToStr (arr, attr) { // 对象数组id属性转为字符串[{id: 1},{id, 2}] to '1,2'
  441. let tempArr = []
  442. arr.forEach(item => {
  443. tempArr.push(item[attr])
  444. })
  445. return tempArr.join(',')
  446. }
  447. /*
  448. * aBC 转 a_b_c
  449. * */
  450. export function underscoreName (s) {
  451. if (!s) {
  452. return null
  453. }
  454. return s.replace(/([A-Z])/g, '_$1').toLowerCase()
  455. }
  456. /*
  457. * a_b_c 转 aBC
  458. * */
  459. export function camelName () {
  460. }
  461. /*
  462. * 上个月1号日期
  463. *
  464. * */
  465. export function lastMonthDate () { // 上个月1号
  466. var Nowdate = new Date()
  467. var vYear = Nowdate.getFullYear()
  468. var vMon = Nowdate.getMonth() + 1
  469. // var vDay = Nowdate.getDate()
  470. // 每个月的最后一天日期(为了使用月份便于查找,数组第一位设为0)
  471. // var daysInMonth = new Array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
  472. if (vMon === 1) {
  473. vYear = Nowdate.getFullYear() - 1
  474. vMon = 12
  475. } else {
  476. vMon = vMon - 1
  477. }
  478. if (vMon < 10) {
  479. vMon = '0' + vMon
  480. }
  481. var date = vYear + '-' + vMon + '-01'
  482. // console.log(date)
  483. return new Date(date)
  484. }