index.js 9.1 KB

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