瀏覽代碼

feat: add utils.js

yhhu 5 年之前
父節點
當前提交
61f002f4d2
共有 4 個文件被更改,包括 58 次插入0 次删除
  1. 0 0
      src/helper.js
  2. 29 0
      src/utils/index.js
  3. 10 0
      src/utils/isPlainObject.js
  4. 19 0
      src/utils/warning.js

+ 0 - 0
src/helper.js


+ 29 - 0
src/utils/index.js

@@ -0,0 +1,29 @@
+import warnning from './warning'
+
+/**
+ * 判断这一年是平年还是闰年
+ * @param {String/Number} year 年份
+ */
+export const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)
+
+/**
+ * 去掉字符串首尾空格
+ * @param {String} str 字符串
+ */
+export const trimStr = str => str.replace(/^\s*/).replace(/\s*$/)
+
+export const formatDate = date => {
+  if (typeof date !== 'string') {
+    warnning('date should be string')
+    return
+  }
+
+  const strArr = trimStr(date).match(/^(\d{4})(\s*[/-\\]\s*)?(\d{2})(\s*[/-\\]\s*)?(\d{2})/)
+  console.log(strArr)
+}
+
+/**
+ * 获取日期中的年份
+ * @param {String} date 日期
+ */
+export const getYear = date => formatDate(date).substr(0, 4)

+ 10 - 0
src/utils/isPlainObject.js

@@ -0,0 +1,10 @@
+export default function isPlainObject(obj) {
+  if (typeof obj !== 'object' || obj === null) return false
+
+  let proto = obj
+  while (Object.getPrototypeOf(proto) !== null) {
+    proto = Object.getPrototypeOf(proto)
+  }
+
+  return Object.getPrototypeOf(obj) === proto
+}

+ 19 - 0
src/utils/warning.js

@@ -0,0 +1,19 @@
+/**
+ * Prints a warning in the console if it exists.
+ *
+ * @param {String} message The warning message.
+ * @returns {void}
+ */
+export function warning(message) {
+  /* eslint-disable no-console */
+  if (typeof console !== 'undefined' && typeof console.error === 'function') {
+    console.error(message)
+  }
+  /* eslint-enable no-console */
+  try {
+    // This error was thrown as a convenience so that if you enable
+    // "break on all exceptions" in your console,
+    // it would pause the execution at this line.
+    throw new Error(message)
+  } catch (e) {} // eslint-disable-line no-empty
+}