index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /**
  2. * Created by PanJiaChen on 16/11/18.
  3. */
  4. /**
  5. * 将时间解析为字符串
  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 || !time) {
  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') {
  20. if (/^[0-9]+$/.test(time)) {
  21. // support "1548221490638"
  22. time = parseInt(time)
  23. } else {
  24. // support safari
  25. // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
  26. time = time.replace(new RegExp(/-/gm), '/')
  27. }
  28. }
  29. if (typeof time === 'number' && time.toString().length === 10) {
  30. time = time * 1000
  31. }
  32. date = new Date(time)
  33. }
  34. const formatObj = {
  35. y: date.getFullYear(),
  36. m: date.getMonth() + 1,
  37. d: date.getDate(),
  38. h: date.getHours(),
  39. i: date.getMinutes(),
  40. s: date.getSeconds(),
  41. a: date.getDay()
  42. }
  43. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  44. const value = formatObj[key]
  45. // Note: getDay() returns 0 on Sunday
  46. if (key === 'a') {
  47. return ['日', '一', '二', '三', '四', '五', '六'][value]
  48. }
  49. return value.toString().padStart(2, '0')
  50. })
  51. return time_str
  52. }
  53. /**
  54. * @param {number} time
  55. * @param {string} option
  56. * @returns {string}
  57. */
  58. export function formatTime(time, option) {
  59. if (('' + time).length === 10) {
  60. time = parseInt(time) * 1000
  61. } else {
  62. time = +time
  63. }
  64. const d = new Date(time)
  65. const now = Date.now()
  66. const diff = (now - d) / 1000
  67. if (diff < 30) {
  68. return '刚刚'
  69. } else if (diff < 3600) {
  70. // less 1 hour
  71. return Math.ceil(diff / 60) + '分钟前'
  72. } else if (diff < 3600 * 24) {
  73. return Math.ceil(diff / 3600) + '小时前'
  74. } else if (diff < 3600 * 24 * 2) {
  75. return '1天前'
  76. }
  77. if (option) {
  78. return parseTime(time, option)
  79. } else {
  80. return (
  81. d.getMonth() +
  82. 1 +
  83. '月' +
  84. d.getDate() +
  85. '日' +
  86. d.getHours() +
  87. '时' +
  88. d.getMinutes() +
  89. '分'
  90. )
  91. }
  92. }
  93. /**
  94. * @param {string} url
  95. * @returns {Object}
  96. */
  97. export function getQueryObject(url) {
  98. url = url == null ? window.location.href : url
  99. const search = url.substring(url.lastIndexOf('?') + 1)
  100. const obj = {}
  101. const reg = /([^?&=]+)=([^?&=]*)/g
  102. search.replace(reg, (rs, $1, $2) => {
  103. const name = decodeURIComponent($1)
  104. let val = decodeURIComponent($2)
  105. val = String(val)
  106. obj[name] = val
  107. return rs
  108. })
  109. return obj
  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. * @param {Array} actual
  128. * @returns {Array}
  129. */
  130. export function cleanArray(actual) {
  131. const newArray = []
  132. for (let i = 0; i < actual.length; i++) {
  133. if (actual[i]) {
  134. newArray.push(actual[i])
  135. }
  136. }
  137. return newArray
  138. }
  139. /**
  140. * @param {Object} json
  141. * @returns {Array}
  142. */
  143. export function param(json) {
  144. if (!json) return ''
  145. return cleanArray(
  146. Object.keys(json).map(key => {
  147. if (json[key] === undefined) return ''
  148. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  149. })
  150. ).join('&')
  151. }
  152. /**
  153. * @param {string} url
  154. * @returns {Object}
  155. */
  156. export function param2Obj(url) {
  157. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  158. if (!search) {
  159. return {}
  160. }
  161. const obj = {}
  162. const searchArr = search.split('&')
  163. searchArr.forEach(v => {
  164. const index = v.indexOf('=')
  165. if (index !== -1) {
  166. const name = v.substring(0, index)
  167. const val = v.substring(index + 1, v.length)
  168. obj[name] = val
  169. }
  170. })
  171. return obj
  172. }
  173. /**
  174. * @param {string} val
  175. * @returns {string}
  176. */
  177. export function html2Text(val) {
  178. const div = document.createElement('div')
  179. div.innerHTML = val
  180. return div.textContent || div.innerText
  181. }
  182. /**
  183. * Merges two objects, giving the last one precedence
  184. * @param {Object} target
  185. * @param {(Object|Array)} source
  186. * @returns {Object}
  187. */
  188. export function objectMerge(target, source) {
  189. if (typeof target !== 'object') {
  190. target = {}
  191. }
  192. if (Array.isArray(source)) {
  193. return source.slice()
  194. }
  195. Object.keys(source).forEach(property => {
  196. const sourceProperty = source[property]
  197. if (typeof sourceProperty === 'object') {
  198. target[property] = objectMerge(target[property], sourceProperty)
  199. } else {
  200. target[property] = sourceProperty
  201. }
  202. })
  203. return target
  204. }
  205. /**
  206. * @param {HTMLElement} element
  207. * @param {string} className
  208. */
  209. export function toggleClass(element, className) {
  210. if (!element || !className) {
  211. return
  212. }
  213. let classString = element.className
  214. const nameIndex = classString.indexOf(className)
  215. if (nameIndex === -1) {
  216. classString += '' + className
  217. } else {
  218. classString =
  219. classString.substr(0, nameIndex) +
  220. classString.substr(nameIndex + className.length)
  221. }
  222. element.className = classString
  223. }
  224. /**
  225. * @param {string} type
  226. * @returns {Date}
  227. */
  228. export function getTime(type) {
  229. if (type === 'start') {
  230. return new Date().getTime() - 3600 * 1000 * 24 * 90
  231. } else {
  232. return new Date(new Date().toDateString())
  233. }
  234. }
  235. /**
  236. * @param {Function} func
  237. * @param {number} wait
  238. * @param {boolean} immediate
  239. * @return {*}
  240. */
  241. export function debounce(func, wait, immediate) {
  242. let timeout, args, context, timestamp, result
  243. const later = function() {
  244. // 据上一次触发时间间隔
  245. const last = +new Date() - timestamp
  246. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  247. if (last < wait && last > 0) {
  248. timeout = setTimeout(later, wait - last)
  249. } else {
  250. timeout = null
  251. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  252. if (!immediate) {
  253. result = func.apply(context, args)
  254. if (!timeout) context = args = null
  255. }
  256. }
  257. }
  258. return function(...args) {
  259. context = this
  260. timestamp = +new Date()
  261. const callNow = immediate && !timeout
  262. // 如果延时不存在,重新设定延时
  263. if (!timeout) timeout = setTimeout(later, wait)
  264. if (callNow) {
  265. result = func.apply(context, args)
  266. context = args = null
  267. }
  268. return result
  269. }
  270. }
  271. /**
  272. * This is just a simple version of deep copy
  273. * Has a lot of edge cases bug
  274. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  275. * @param {Object} source
  276. * @returns {Object}
  277. */
  278. export function deepClone(source) {
  279. if (!source && typeof source !== 'object') {
  280. throw new Error('error arguments', 'deepClone')
  281. }
  282. const targetObj = source.constructor === Array ? [] : {}
  283. Object.keys(source).forEach(keys => {
  284. if (source[keys] && typeof source[keys] === 'object') {
  285. targetObj[keys] = deepClone(source[keys])
  286. } else {
  287. targetObj[keys] = source[keys]
  288. }
  289. })
  290. return targetObj
  291. }
  292. /**
  293. * @param {Array} arr
  294. * @returns {Array}
  295. */
  296. export function uniqueArr(arr) {
  297. return Array.from(new Set(arr))
  298. }
  299. /**
  300. * @returns {string}
  301. */
  302. export function createUniqueString() {
  303. const timestamp = +new Date() + ''
  304. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  305. return (+(randomNum + timestamp)).toString(32)
  306. }
  307. /**
  308. * Check if an element has a class
  309. * @param {HTMLElement} elm
  310. * @param {string} cls
  311. * @returns {boolean}
  312. */
  313. export function hasClass(ele, cls) {
  314. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  315. }
  316. /**
  317. * Add class to element
  318. * @param {HTMLElement} elm
  319. * @param {string} cls
  320. */
  321. export function addClass(ele, cls) {
  322. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  323. }
  324. /**
  325. * Remove class from element
  326. * @param {HTMLElement} elm
  327. * @param {string} cls
  328. */
  329. export function removeClass(ele, cls) {
  330. if (hasClass(ele, cls)) {
  331. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  332. ele.className = ele.className.replace(reg, ' ')
  333. }
  334. }