exam.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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}
  9. */
  10. export function parseTime(time, cFormat) {
  11. if (arguments.length === 0) {
  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' && /^[0-9]+$/.test(time)) {
  20. time = parseInt(time)
  21. }
  22. if (typeof time === 'number' && time.toString().length === 10) {
  23. time = time * 1000
  24. }
  25. date = new Date(time)
  26. }
  27. const formatObj = {
  28. y: date.getFullYear(),
  29. m: date.getMonth() + 1,
  30. d: date.getDate(),
  31. h: date.getHours(),
  32. i: date.getMinutes(),
  33. s: date.getSeconds(),
  34. a: date.getDay()
  35. }
  36. // eslint-disable-next-line camelcase
  37. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  38. let value = formatObj[key]
  39. // Note: getDay() returns 0 on Sunday
  40. if (key === 'a') {
  41. return ['日', '一', '二', '三', '四', '五', '六'][value]
  42. }
  43. if (result.length > 0 && value < 10) {
  44. value = '0' + value
  45. }
  46. return value || 0
  47. })
  48. // eslint-disable-next-line camelcase
  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 d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  79. }
  80. }
  81. /**
  82. * @param {string} url
  83. * @returns {Object}
  84. */
  85. export function getQueryObject(url) {
  86. url = url == null ? window.location.href : url
  87. const search = url.substring(url.lastIndexOf('?') + 1)
  88. const obj = {}
  89. const reg = /([^?&=]+)=([^?&=]*)/g
  90. search.replace(reg, (rs, $1, $2) => {
  91. const name = decodeURIComponent($1)
  92. let val = decodeURIComponent($2)
  93. val = String(val)
  94. obj[name] = val
  95. return rs
  96. })
  97. return obj
  98. }
  99. /**
  100. * @param {string} input value
  101. * @returns {number} output value
  102. */
  103. export function byteLength(str) {
  104. // returns the byte length of an utf8 string
  105. let s = str.length
  106. for (var i = str.length - 1; i >= 0; i--) {
  107. const code = str.charCodeAt(i)
  108. if (code > 0x7f && code <= 0x7ff) s++
  109. else if (code > 0x7ff && code <= 0xffff) s += 2
  110. if (code >= 0xdc00 && code <= 0xdfff) i--
  111. }
  112. return s
  113. }
  114. /**
  115. * @param {Array} actual
  116. * @returns {Array}
  117. */
  118. export function cleanArray(actual) {
  119. const newArray = []
  120. for (let i = 0; i < actual.length; i++) {
  121. if (actual[i]) {
  122. newArray.push(actual[i])
  123. }
  124. }
  125. return newArray
  126. }
  127. /**
  128. * @param {Object} json
  129. * @returns {Array}
  130. */
  131. export function param(json) {
  132. if (!json) return ''
  133. return cleanArray(
  134. Object.keys(json).map((key) => {
  135. if (json[key] === undefined) return ''
  136. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  137. })
  138. ).join('&')
  139. }
  140. /**
  141. * @param {string} url
  142. * @returns {Object}
  143. */
  144. export function param2Obj(url) {
  145. const search = url.split('?')[1]
  146. if (!search) {
  147. return {}
  148. }
  149. return JSON.parse(
  150. '{"' +
  151. decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ') +
  152. '"}'
  153. )
  154. }
  155. /**
  156. * @param {string} val
  157. * @returns {string}
  158. */
  159. export function html2Text(val) {
  160. const div = document.createElement('div')
  161. div.innerHTML = val
  162. return div.textContent || div.innerText
  163. }
  164. /**
  165. * Merges two objects, giving the last one precedence
  166. * @param {Object} target
  167. * @param {(Object|Array)} source
  168. * @returns {Object}
  169. */
  170. export function objectMerge(target, source) {
  171. if (typeof target !== 'object') {
  172. target = {}
  173. }
  174. if (Array.isArray(source)) {
  175. return source.slice()
  176. }
  177. Object.keys(source).forEach((property) => {
  178. const sourceProperty = source[property]
  179. if (typeof sourceProperty === 'object') {
  180. target[property] = objectMerge(target[property], sourceProperty)
  181. } else {
  182. target[property] = sourceProperty
  183. }
  184. })
  185. return target
  186. }
  187. /**
  188. * @param {HTMLElement} element
  189. * @param {string} className
  190. */
  191. export function toggleClass(element, className) {
  192. if (!element || !className) {
  193. return
  194. }
  195. let classString = element.className
  196. const nameIndex = classString.indexOf(className)
  197. if (nameIndex === -1) {
  198. classString += '' + className
  199. } else {
  200. classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  201. }
  202. element.className = classString
  203. }
  204. /**
  205. * @param {string} type
  206. * @returns {Date}
  207. */
  208. export function getTime(type) {
  209. if (type === 'start') {
  210. return new Date().getTime() - 3600 * 1000 * 24 * 90
  211. } else {
  212. return new Date(new Date().toDateString())
  213. }
  214. }
  215. /**
  216. * @param {Function} func
  217. * @param {number} wait
  218. * @param {boolean} immediate
  219. * @return {*}
  220. */
  221. export function debounce(func, wait, immediate) {
  222. let timeout, args, context, timestamp, result
  223. const later = function () {
  224. // 据上一次触发时间间隔
  225. const last = +new Date() - timestamp
  226. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  227. if (last < wait && last > 0) {
  228. timeout = setTimeout(later, wait - last)
  229. } else {
  230. timeout = null
  231. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  232. if (!immediate) {
  233. result = func.apply(context, args)
  234. if (!timeout) context = args = null
  235. }
  236. }
  237. }
  238. return function (...args) {
  239. context = this
  240. timestamp = +new Date()
  241. const callNow = immediate && !timeout
  242. // 如果延时不存在,重新设定延时
  243. if (!timeout) timeout = setTimeout(later, wait)
  244. if (callNow) {
  245. result = func.apply(context, args)
  246. context = args = null
  247. }
  248. return result
  249. }
  250. }
  251. /**
  252. * This is just a simple version of deep copy
  253. * Has a lot of edge cases bug
  254. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  255. * @param {Object} source
  256. * @returns {Object}
  257. */
  258. export function deepClone(source) {
  259. if (!source && typeof source !== 'object') {
  260. throw new Error('error arguments', 'deepClone')
  261. }
  262. const targetObj = source.constructor === Array ? [] : {}
  263. Object.keys(source).forEach((keys) => {
  264. if (source[keys] && typeof source[keys] === 'object') {
  265. targetObj[keys] = deepClone(source[keys])
  266. } else {
  267. targetObj[keys] = source[keys]
  268. }
  269. })
  270. return targetObj
  271. }
  272. /**
  273. * @param {Array} arr
  274. * @returns {Array}
  275. */
  276. export function uniqueArr(arr) {
  277. return Array.from(new Set(arr))
  278. }
  279. /**
  280. * @returns {string}
  281. */
  282. export function createUniqueString() {
  283. const timestamp = +new Date() + ''
  284. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  285. return (+(randomNum + timestamp)).toString(32)
  286. }
  287. /**
  288. * Check if an element has a class
  289. * @param {HTMLElement} elm
  290. * @param {string} cls
  291. * @returns {boolean}
  292. */
  293. export function hasClass(ele, cls) {
  294. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  295. }
  296. /**
  297. * Add class to element
  298. * @param {HTMLElement} elm
  299. * @param {string} cls
  300. */
  301. export function addClass(ele, cls) {
  302. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  303. }
  304. /**
  305. * Remove class from element
  306. * @param {HTMLElement} elm
  307. * @param {string} cls
  308. */
  309. export function removeClass(ele, cls) {
  310. if (hasClass(ele, cls)) {
  311. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  312. ele.className = ele.className.replace(reg, ' ')
  313. }
  314. }
  315. export function formatSeconds(theTime) {
  316. let theTime1 = 0
  317. let theTime2 = 0
  318. if (theTime > 60) {
  319. theTime1 = parseInt(theTime / 60)
  320. theTime = parseInt(theTime % 60)
  321. if (theTime1 > 60) {
  322. theTime2 = parseInt(theTime1 / 60)
  323. theTime1 = parseInt(theTime1 % 60)
  324. }
  325. }
  326. let result = '' + parseInt(theTime) + '秒'
  327. if (theTime1 > 0) {
  328. result = '' + parseInt(theTime1) + '分' + result
  329. }
  330. if (theTime2 > 0) {
  331. result = '' + parseInt(theTime2) + '小时' + result
  332. }
  333. return result
  334. }