index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. }