index.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /**
  2. * 表格时间格式化
  3. */
  4. export function formatDate(cellValue) {
  5. if (cellValue == null || cellValue == "") return "";
  6. var date = new Date(cellValue)
  7. var year = date.getFullYear()
  8. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  9. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  10. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  11. var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  12. var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  13. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  14. }
  15. /**
  16. * @param {number} time
  17. * @param {string} option
  18. * @returns {string}
  19. */
  20. export function formatTime(time, option) {
  21. if (('' + time).length === 10) {
  22. time = parseInt(time) * 1000
  23. } else {
  24. time = +time
  25. }
  26. const d = new Date(time)
  27. const now = Date.now()
  28. const diff = (now - d) / 1000
  29. if (diff < 30) {
  30. return '刚刚'
  31. } else if (diff < 3600) {
  32. // less 1 hour
  33. return Math.ceil(diff / 60) + '分钟前'
  34. } else if (diff < 3600 * 24) {
  35. return Math.ceil(diff / 3600) + '小时前'
  36. } else if (diff < 3600 * 24 * 2) {
  37. return '1天前'
  38. }
  39. if (option) {
  40. return parseTime(time, option)
  41. } else {
  42. return (
  43. d.getMonth() +
  44. 1 +
  45. '月' +
  46. d.getDate() +
  47. '日' +
  48. d.getHours() +
  49. '时' +
  50. d.getMinutes() +
  51. '分'
  52. )
  53. }
  54. }
  55. /**
  56. * @param {string} url
  57. * @returns {Object}
  58. */
  59. export function getQueryObject(url) {
  60. url = url == null ? window.location.href : url
  61. const search = url.substring(url.lastIndexOf('?') + 1)
  62. const obj = {}
  63. const reg = /([^?&=]+)=([^?&=]*)/g
  64. search.replace(reg, (rs, $1, $2) => {
  65. const name = decodeURIComponent($1)
  66. let val = decodeURIComponent($2)
  67. val = String(val)
  68. obj[name] = val
  69. return rs
  70. })
  71. return obj
  72. }
  73. /**
  74. * @param {string} input value
  75. * @returns {number} output value
  76. */
  77. export function byteLength(str) {
  78. // returns the byte length of an utf8 string
  79. let s = str.length
  80. for (var i = str.length - 1; i >= 0; i--) {
  81. const code = str.charCodeAt(i)
  82. if (code > 0x7f && code <= 0x7ff) s++
  83. else if (code > 0x7ff && code <= 0xffff) s += 2
  84. if (code >= 0xDC00 && code <= 0xDFFF) i--
  85. }
  86. return s
  87. }
  88. /**
  89. * @param {Array} actual
  90. * @returns {Array}
  91. */
  92. export function cleanArray(actual) {
  93. const newArray = []
  94. for (let i = 0; i < actual.length; i++) {
  95. if (actual[i]) {
  96. newArray.push(actual[i])
  97. }
  98. }
  99. return newArray
  100. }
  101. /**
  102. * @param {Object} json
  103. * @returns {Array}
  104. */
  105. export function param(json) {
  106. if (!json) return ''
  107. return cleanArray(
  108. Object.keys(json).map(key => {
  109. if (json[key] === undefined) return ''
  110. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  111. })
  112. ).join('&')
  113. }
  114. /**
  115. * @param {string} url
  116. * @returns {Object}
  117. */
  118. export function param2Obj(url) {
  119. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  120. if (!search) {
  121. return {}
  122. }
  123. const obj = {}
  124. const searchArr = search.split('&')
  125. searchArr.forEach(v => {
  126. const index = v.indexOf('=')
  127. if (index !== -1) {
  128. const name = v.substring(0, index)
  129. const val = v.substring(index + 1, v.length)
  130. obj[name] = val
  131. }
  132. })
  133. return obj
  134. }
  135. /**
  136. * @param {string} val
  137. * @returns {string}
  138. */
  139. export function html2Text(val) {
  140. const div = document.createElement('div')
  141. div.innerHTML = val
  142. return div.textContent || div.innerText
  143. }
  144. /**
  145. * Merges two objects, giving the last one precedence
  146. * @param {Object} target
  147. * @param {(Object|Array)} source
  148. * @returns {Object}
  149. */
  150. export function objectMerge(target, source) {
  151. if (typeof target !== 'object') {
  152. target = {}
  153. }
  154. if (Array.isArray(source)) {
  155. return source.slice()
  156. }
  157. Object.keys(source).forEach(property => {
  158. const sourceProperty = source[property]
  159. if (typeof sourceProperty === 'object') {
  160. target[property] = objectMerge(target[property], sourceProperty)
  161. } else {
  162. target[property] = sourceProperty
  163. }
  164. })
  165. return target
  166. }
  167. /**
  168. * @param {HTMLElement} element
  169. * @param {string} className
  170. */
  171. export function toggleClass(element, className) {
  172. if (!element || !className) {
  173. return
  174. }
  175. let classString = element.className
  176. const nameIndex = classString.indexOf(className)
  177. if (nameIndex === -1) {
  178. classString += '' + className
  179. } else {
  180. classString =
  181. classString.substr(0, nameIndex) +
  182. classString.substr(nameIndex + className.length)
  183. }
  184. element.className = classString
  185. }
  186. /**
  187. * @param {string} type
  188. * @returns {Date}
  189. */
  190. export function getTime(type) {
  191. if (type === 'start') {
  192. return new Date().getTime() - 3600 * 1000 * 24 * 90
  193. } else {
  194. return new Date(new Date().toDateString())
  195. }
  196. }
  197. /**
  198. * @param {Function} func
  199. * @param {number} wait
  200. * @param {boolean} immediate
  201. * @return {*}
  202. */
  203. export function debounce(func, wait, immediate) {
  204. let timeout, args, context, timestamp, result
  205. const later = function() {
  206. // 据上一次触发时间间隔
  207. const last = +new Date() - timestamp
  208. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  209. if (last < wait && last > 0) {
  210. timeout = setTimeout(later, wait - last)
  211. } else {
  212. timeout = null
  213. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  214. if (!immediate) {
  215. result = func.apply(context, args)
  216. if (!timeout) context = args = null
  217. }
  218. }
  219. }
  220. return function(...args) {
  221. context = this
  222. timestamp = +new Date()
  223. const callNow = immediate && !timeout
  224. // 如果延时不存在,重新设定延时
  225. if (!timeout) timeout = setTimeout(later, wait)
  226. if (callNow) {
  227. result = func.apply(context, args)
  228. context = args = null
  229. }
  230. return result
  231. }
  232. }
  233. /**
  234. * This is just a simple version of deep copy
  235. * Has a lot of edge cases bug
  236. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  237. * @param {Object} source
  238. * @returns {Object}
  239. */
  240. export function deepClone(source) {
  241. if (!source && typeof source !== 'object') {
  242. throw new Error('error arguments', 'deepClone')
  243. }
  244. const targetObj = source.constructor === Array ? [] : {}
  245. Object.keys(source).forEach(keys => {
  246. if (source[keys] && typeof source[keys] === 'object') {
  247. targetObj[keys] = deepClone(source[keys])
  248. } else {
  249. targetObj[keys] = source[keys]
  250. }
  251. })
  252. return targetObj
  253. }
  254. /**
  255. * @param {Array} arr
  256. * @returns {Array}
  257. */
  258. export function uniqueArr(arr) {
  259. return Array.from(new Set(arr))
  260. }
  261. /**
  262. * @returns {string}
  263. */
  264. export function createUniqueString() {
  265. const timestamp = +new Date() + ''
  266. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  267. return (+(randomNum + timestamp)).toString(32)
  268. }
  269. /**
  270. * Check if an element has a class
  271. * @param {HTMLElement} elm
  272. * @param {string} cls
  273. * @returns {boolean}
  274. */
  275. export function hasClass(ele, cls) {
  276. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  277. }
  278. /**
  279. * Add class to element
  280. * @param {HTMLElement} elm
  281. * @param {string} cls
  282. */
  283. export function addClass(ele, cls) {
  284. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  285. }
  286. /**
  287. * Remove class from element
  288. * @param {HTMLElement} elm
  289. * @param {string} cls
  290. */
  291. export function removeClass(ele, cls) {
  292. if (hasClass(ele, cls)) {
  293. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  294. ele.className = ele.className.replace(reg, ' ')
  295. }
  296. }
  297. export function makeMap(str, expectsLowerCase) {
  298. const map = Object.create(null)
  299. const list = str.split(',')
  300. for (let i = 0; i < list.length; i++) {
  301. map[list[i]] = true
  302. }
  303. return expectsLowerCase
  304. ? val => map[val.toLowerCase()]
  305. : val => map[val]
  306. }
  307. export const exportDefault = 'export default '
  308. export const beautifierConf = {
  309. html: {
  310. indent_size: '2',
  311. indent_char: ' ',
  312. max_preserve_newlines: '-1',
  313. preserve_newlines: false,
  314. keep_array_indentation: false,
  315. break_chained_methods: false,
  316. indent_scripts: 'separate',
  317. brace_style: 'end-expand',
  318. space_before_conditional: true,
  319. unescape_strings: false,
  320. jslint_happy: false,
  321. end_with_newline: true,
  322. wrap_line_length: '110',
  323. indent_inner_html: true,
  324. comma_first: false,
  325. e4x: true,
  326. indent_empty_lines: true
  327. },
  328. js: {
  329. indent_size: '2',
  330. indent_char: ' ',
  331. max_preserve_newlines: '-1',
  332. preserve_newlines: false,
  333. keep_array_indentation: false,
  334. break_chained_methods: false,
  335. indent_scripts: 'normal',
  336. brace_style: 'end-expand',
  337. space_before_conditional: true,
  338. unescape_strings: false,
  339. jslint_happy: true,
  340. end_with_newline: true,
  341. wrap_line_length: '110',
  342. indent_inner_html: true,
  343. comma_first: false,
  344. e4x: true,
  345. indent_empty_lines: true
  346. }
  347. }
  348. // 首字母大小
  349. export function titleCase(str) {
  350. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  351. }
  352. // 下划转驼峰
  353. export function camelCase(str) {
  354. return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  355. }
  356. export function isNumberStr(str) {
  357. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  358. }