index.js 9.7 KB

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