index.ts 9.5 KB

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