utils.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. export function isArray(value) {
  2. if (typeof Array.isArray === 'function') {
  3. return Array.isArray(value);
  4. } else {
  5. return Object.prototype.toString.call(value) === '[object Array]';
  6. }
  7. }
  8. export function isObject(value) {
  9. return Object.prototype.toString.call(value) === '[object Object]';
  10. }
  11. export function isNumber(value) {
  12. return !isNaN(Number(value));
  13. }
  14. export function isFunction(value) {
  15. return typeof value == 'function';
  16. }
  17. export function isString(value) {
  18. return typeof value == 'string';
  19. }
  20. export function isEmpty(value) {
  21. if (value === '' || value === undefined || value === null) {
  22. return true;
  23. }
  24. if (isArray(value)) {
  25. return value.length === 0;
  26. }
  27. if (isObject(value)) {
  28. return Object.keys(value).length === 0;
  29. }
  30. return false;
  31. }
  32. export function isBoolean(value) {
  33. return typeof value === 'boolean';
  34. }
  35. export function last(data) {
  36. if (isArray(data) || isString(data)) {
  37. return data[data.length - 1];
  38. }
  39. }
  40. export function cloneDeep(obj) {
  41. const d = isArray(obj) ? [...obj] : {};
  42. if (isObject(obj)) {
  43. for (const key in obj) {
  44. if (obj[key]) {
  45. if (obj[key] && typeof obj[key] === 'object') {
  46. d[key] = cloneDeep(obj[key]);
  47. } else {
  48. d[key] = obj[key];
  49. }
  50. }
  51. }
  52. }
  53. return d;
  54. }
  55. export function clone(obj) {
  56. return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
  57. }
  58. export function deepMerge(a, b) {
  59. let k;
  60. for (k in b) {
  61. a[k] = a[k] && a[k].toString() === '[object Object]' ? deepMerge(a[k], b[k]) : (a[k] = b[k]);
  62. }
  63. return a;
  64. }
  65. export function contains(parent, node) {
  66. while (node && (node = node.parentNode)) if (node === parent) return true;
  67. return false;
  68. }
  69. export function orderBy(list, key) {
  70. return list.sort((a, b) => a[key] - b[key]);
  71. }
  72. export function deepTree(list) {
  73. const newList = [];
  74. const map = {};
  75. list.forEach((e) => (map[e.id] = e));
  76. list.forEach((e) => {
  77. const parent = map[e.parentId];
  78. if (parent) {
  79. (parent.children || (parent.children = [])).push(e);
  80. } else {
  81. newList.push(e);
  82. }
  83. });
  84. const fn = (list) => {
  85. list.map((e) => {
  86. if (e.children instanceof Array) {
  87. e.children = orderBy(e.children, 'orderNum');
  88. fn(e.children);
  89. }
  90. });
  91. };
  92. fn(newList);
  93. return orderBy(newList, 'orderNum');
  94. }
  95. export function revDeepTree(list = []) {
  96. const d = [];
  97. let id = 0;
  98. const deep = (list, parentId) => {
  99. list.forEach((e) => {
  100. if (!e.id) {
  101. e.id = id++;
  102. }
  103. e.parentId = parentId;
  104. d.push(e);
  105. if (e.children && isArray(e.children)) {
  106. deep(e.children, e.id);
  107. }
  108. });
  109. };
  110. deep(list || [], null);
  111. return d;
  112. }
  113. export function basename(path) {
  114. let index = path.lastIndexOf('/');
  115. index = index > -1 ? index : path.lastIndexOf('\\');
  116. if (index < 0) {
  117. return path;
  118. }
  119. return path.substring(index + 1);
  120. }
  121. export function isWxBrowser() {
  122. const ua = navigator.userAgent.toLowerCase();
  123. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  124. return true;
  125. } else {
  126. return false;
  127. }
  128. }
  129. /**
  130. * @description 如果value小于min,取min;如果value大于max,取max
  131. * @param {number} min
  132. * @param {number} max
  133. * @param {number} value
  134. */
  135. export function range(min = 0, max = 0, value = 0) {
  136. return Math.max(min, Math.min(max, Number(value)));
  137. }
  138. import dayjs from 'dayjs';
  139. /**
  140. * 将一个整数转换为分数保留两位小数
  141. * @param {number | string | undefined} num 整数
  142. * @return {number} 分数
  143. */
  144. export const formatToFraction = (num) => {
  145. if (typeof num === 'undefined') return 0;
  146. const parsedNumber = typeof num === 'string' ? parseFloat(num) : num;
  147. return parseFloat((parsedNumber / 100).toFixed(2));
  148. };
  149. /**
  150. * 将一个数转换为 1.00 这样
  151. * 数据呈现的时候使用
  152. *
  153. * @param {number | string | undefined} num 整数
  154. * @return {string} 分数
  155. */
  156. export const floatToFixed2 = (num) => {
  157. let str = '0.00';
  158. if (typeof num === 'undefined') {
  159. return str;
  160. }
  161. const f = formatToFraction(num);
  162. const decimalPart = f.toString().split('.')[1];
  163. const len = decimalPart ? decimalPart.length : 0;
  164. switch (len) {
  165. case 0:
  166. str = f.toString() + '.00';
  167. break;
  168. case 1:
  169. str = f.toString() + '.0';
  170. break;
  171. case 2:
  172. str = f.toString();
  173. break;
  174. }
  175. return str;
  176. };
  177. /**
  178. * 时间日期转换
  179. * @param {dayjs.ConfigType} date 当前时间,new Date() 格式
  180. * @param {string} format 需要转换的时间格式字符串
  181. * @description format 字符串随意,如 `YYYY-mm、YYYY-mm-dd`
  182. * @description format 季度:"YYYY-mm-dd HH:MM:SS QQQQ"
  183. * @description format 星期:"YYYY-mm-dd HH:MM:SS WWW"
  184. * @description format 几周:"YYYY-mm-dd HH:MM:SS ZZZ"
  185. * @description format 季度 + 星期 + 几周:"YYYY-mm-dd HH:MM:SS WWW QQQQ ZZZ"
  186. * @returns {string} 返回拼接后的时间字符串
  187. */
  188. export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  189. // 日期不存在,则返回空
  190. if (!date) {
  191. return '';
  192. }
  193. // 日期存在,则进行格式化
  194. if (format === undefined) {
  195. format = 'YYYY-MM-DD HH:mm:ss';
  196. }
  197. return dayjs(date).format(format);
  198. }
  199. /**
  200. * 构造树型结构数据
  201. *
  202. * @param {*} data 数据源
  203. * @param {*} id id字段 默认 'id'
  204. * @param {*} parentId 父节点字段 默认 'parentId'
  205. * @param {*} children 孩子节点字段 默认 'children'
  206. * @param {*} rootId 根Id 默认 0
  207. */
  208. export function handleTree(
  209. data,
  210. id = 'id',
  211. parentId = 'parentId',
  212. children = 'children',
  213. rootId = 0,
  214. ) {
  215. // 对源数据深度克隆
  216. const cloneData = JSON.parse(JSON.stringify(data));
  217. // 循环所有项
  218. const treeData = cloneData.filter((father) => {
  219. let branchArr = cloneData.filter((child) => {
  220. //返回每一项的子级数组
  221. return father[id] === child[parentId];
  222. });
  223. branchArr.length > 0 ? (father.children = branchArr) : '';
  224. //返回第一层
  225. return father[parentId] === rootId;
  226. });
  227. return treeData !== '' ? treeData : data;
  228. }
  229. /**
  230. * 重置分页对象
  231. *
  232. * @param pagination 分页对象
  233. */
  234. export function resetPagination(pagination) {
  235. pagination.list = [];
  236. pagination.total = 0;
  237. pagination.page = 1;
  238. }
  239. /**
  240. * 将值复制到目标对象,且以目标对象属性为准,例:target: {a:1} source:{a:2,b:3} 结果为:{a:2}
  241. * @param target 目标对象
  242. * @param source 源对象
  243. */
  244. export const copyValueToTarget = (target, source) => {
  245. const newObj = Object.assign({}, target, source);
  246. // 删除多余属性
  247. Object.keys(newObj).forEach((key) => {
  248. // 如果不是target中的属性则删除
  249. if (Object.keys(target).indexOf(key) === -1) {
  250. delete newObj[key];
  251. }
  252. });
  253. // 更新目标对象值
  254. Object.assign(target, newObj);
  255. };
  256. /**
  257. * 解析 JSON 字符串
  258. *
  259. * @param str
  260. */
  261. export function jsonParse(str) {
  262. try {
  263. return JSON.parse(str);
  264. } catch (e) {
  265. console.warn(`str[${str}] 不是一个 JSON 字符串`);
  266. return str;
  267. }
  268. }
  269. /**
  270. * 获得当前周的开始和结束时间
  271. */
  272. export function getWeekTimes() {
  273. const today = new Date();
  274. const dayOfWeek = today.getDay();
  275. return [
  276. new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek, 0, 0, 0),
  277. new Date(today.getFullYear(), today.getMonth(), today.getDate() + (6 - dayOfWeek), 23, 59, 59),
  278. ];
  279. }
  280. /**
  281. * 获得当前月的开始和结束时间
  282. */
  283. export function getMonthTimes() {
  284. const today = new Date();
  285. const year = today.getFullYear();
  286. const month = today.getMonth();
  287. const startDate = new Date(year, month, 1, 0, 0, 0);
  288. const nextMonth = new Date(year, month + 1, 1);
  289. const endDate = new Date(nextMonth.getTime() - 1);
  290. return [startDate, endDate];
  291. }