index.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 = url.split('?')[1]
  120. if (!search) {
  121. return {}
  122. }
  123. return JSON.parse(
  124. '{"' +
  125. decodeURIComponent(search)
  126. .replace(/"/g, '\\"')
  127. .replace(/&/g, '","')
  128. .replace(/=/g, '":"')
  129. .replace(/\+/g, ' ') +
  130. '"}'
  131. )
  132. }
  133. /**
  134. * @param {string} val
  135. * @returns {string}
  136. */
  137. export function html2Text(val) {
  138. const div = document.createElement('div')
  139. div.innerHTML = val
  140. return div.textContent || div.innerText
  141. }
  142. /**
  143. * Merges two objects, giving the last one precedence
  144. * @param {Object} target
  145. * @param {(Object|Array)} source
  146. * @returns {Object}
  147. */
  148. export function objectMerge(target, source) {
  149. if (typeof target !== 'object') {
  150. target = {}
  151. }
  152. if (Array.isArray(source)) {
  153. return source.slice()
  154. }
  155. Object.keys(source).forEach(property => {
  156. const sourceProperty = source[property]
  157. if (typeof sourceProperty === 'object') {
  158. target[property] = objectMerge(target[property], sourceProperty)
  159. } else {
  160. target[property] = sourceProperty
  161. }
  162. })
  163. return target
  164. }
  165. /**
  166. * @param {HTMLElement} element
  167. * @param {string} className
  168. */
  169. export function toggleClass(element, className) {
  170. if (!element || !className) {
  171. return
  172. }
  173. let classString = element.className
  174. const nameIndex = classString.indexOf(className)
  175. if (nameIndex === -1) {
  176. classString += '' + className
  177. } else {
  178. classString =
  179. classString.substr(0, nameIndex) +
  180. classString.substr(nameIndex + className.length)
  181. }
  182. element.className = classString
  183. }
  184. /**
  185. * @param {string} type
  186. * @returns {Date}
  187. */
  188. export function getTime(type) {
  189. if (type === 'start') {
  190. return new Date().getTime() - 3600 * 1000 * 24 * 90
  191. } else {
  192. return new Date(new Date().toDateString())
  193. }
  194. }
  195. /**
  196. * @param {Function} func
  197. * @param {number} wait
  198. * @param {boolean} immediate
  199. * @return {*}
  200. */
  201. export function debounce(func, wait, immediate) {
  202. let timeout, args, context, timestamp, result
  203. const later = function() {
  204. // 据上一次触发时间间隔
  205. const last = +new Date() - timestamp
  206. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  207. if (last < wait && last > 0) {
  208. timeout = setTimeout(later, wait - last)
  209. } else {
  210. timeout = null
  211. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  212. if (!immediate) {
  213. result = func.apply(context, args)
  214. if (!timeout) context = args = null
  215. }
  216. }
  217. }
  218. return function(...args) {
  219. context = this
  220. timestamp = +new Date()
  221. const callNow = immediate && !timeout
  222. // 如果延时不存在,重新设定延时
  223. if (!timeout) timeout = setTimeout(later, wait)
  224. if (callNow) {
  225. result = func.apply(context, args)
  226. context = args = null
  227. }
  228. return result
  229. }
  230. }
  231. /**
  232. * This is just a simple version of deep copy
  233. * Has a lot of edge cases bug
  234. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  235. * @param {Object} source
  236. * @returns {Object}
  237. */
  238. export function deepClone(source) {
  239. if (!source && typeof source !== 'object') {
  240. throw new Error('error arguments', 'deepClone')
  241. }
  242. const targetObj = source.constructor === Array ? [] : {}
  243. Object.keys(source).forEach(keys => {
  244. if (source[keys] && typeof source[keys] === 'object') {
  245. targetObj[keys] = deepClone(source[keys])
  246. } else {
  247. targetObj[keys] = source[keys]
  248. }
  249. })
  250. return targetObj
  251. }
  252. /**
  253. * @param {Array} arr
  254. * @returns {Array}
  255. */
  256. export function uniqueArr(arr) {
  257. return Array.from(new Set(arr))
  258. }
  259. /**
  260. * @returns {string}
  261. */
  262. export function createUniqueString() {
  263. const timestamp = +new Date() + ''
  264. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  265. return (+(randomNum + timestamp)).toString(32)
  266. }
  267. /**
  268. * Check if an element has a class
  269. * @param {HTMLElement} elm
  270. * @param {string} cls
  271. * @returns {boolean}
  272. */
  273. export function hasClass(ele, cls) {
  274. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  275. }
  276. /**
  277. * Add class to element
  278. * @param {HTMLElement} elm
  279. * @param {string} cls
  280. */
  281. export function addClass(ele, cls) {
  282. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  283. }
  284. /**
  285. * Remove class from element
  286. * @param {HTMLElement} elm
  287. * @param {string} cls
  288. */
  289. export function removeClass(ele, cls) {
  290. if (hasClass(ele, cls)) {
  291. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  292. ele.className = ele.className.replace(reg, ' ')
  293. }
  294. }
  295. export function makeMap(str, expectsLowerCase) {
  296. const map = Object.create(null)
  297. const list = str.split(',')
  298. for (let i = 0; i < list.length; i++) {
  299. map[list[i]] = true
  300. }
  301. return expectsLowerCase
  302. ? val => map[val.toLowerCase()]
  303. : val => map[val]
  304. }
  305. export const exportDefault = 'export default '
  306. export const beautifierConf = {
  307. html: {
  308. indent_size: '2',
  309. indent_char: ' ',
  310. max_preserve_newlines: '-1',
  311. preserve_newlines: false,
  312. keep_array_indentation: false,
  313. break_chained_methods: false,
  314. indent_scripts: 'separate',
  315. brace_style: 'end-expand',
  316. space_before_conditional: true,
  317. unescape_strings: false,
  318. jslint_happy: false,
  319. end_with_newline: true,
  320. wrap_line_length: '110',
  321. indent_inner_html: true,
  322. comma_first: false,
  323. e4x: true,
  324. indent_empty_lines: true
  325. },
  326. js: {
  327. indent_size: '2',
  328. indent_char: ' ',
  329. max_preserve_newlines: '-1',
  330. preserve_newlines: false,
  331. keep_array_indentation: false,
  332. break_chained_methods: false,
  333. indent_scripts: 'normal',
  334. brace_style: 'end-expand',
  335. space_before_conditional: true,
  336. unescape_strings: false,
  337. jslint_happy: true,
  338. end_with_newline: true,
  339. wrap_line_length: '110',
  340. indent_inner_html: true,
  341. comma_first: false,
  342. e4x: true,
  343. indent_empty_lines: true
  344. }
  345. }
  346. // 首字母大小
  347. export function titleCase(str) {
  348. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  349. }
  350. // 下划转驼峰
  351. export function camelCase(str) {
  352. return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  353. }
  354. export function isNumberStr(str) {
  355. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  356. }