- 深拷贝
import _ from 'underscore'
interface DAMNU_ENABLE {
[key: string]: string | boolean | DAMNU_ENABLE | number
}
function formatRequestParams(params: DAMNU_ENABLE): DAMNU_ENABLE {
const result: DAMNU_ENABLE = {}
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
const value = params[key]
// 对象且不为 null function
if (typeof value === 'object' && !_.isNull(value) && !_.isFunction(value)) {
result[key] = formatRequestParams(value)
}
if (typeof value === 'string' && value.trim().length !== 0) {
//
result[key] = value
}
if (_.isNumber(value)) {
result[key] = value
}
}
}
return result
}
2. 将数字n分割成x份,并且每份的数都是整数,且大于等于 n / (2 * x),小于等于 2 * n / x,编写一个算法
// 获取之和为 n 的 x 个数数组序列
const getParsedArray = (n, x, result = []) => {
if (x === 1) return [n]
for (let i = 1; i < n; i++) {
result.push([i, ...getParsedArray(n - i, x - 1)])
}
return result
}
const mergeToResult = res => {
if (res.length === 1) return res
const result = []
res.map(firstItem => {
const temp = firstItem[0]
if (typeof firstItem[1] !== 'number') {
firstItem.map((secondItem, index) => {
if (index !== 0) {
result.push([temp, ...secondItem])
}
})
} else {
result.push(firstItem)
}
})
return result
}
const splitNumberToArray = (num, x) => {
if (x === 1) return [num]
const start = num / 2 / x
const end = (2 * num) / x
const result = mergeToResult(getParsedArray(num, x))
return result.filter(item => item.every(item1 => item1 >= start && item1 <= end))
}
3. 日期格式化
const formatDate = date => {
const d = new Date(date)
const year = d.getFullYear()
let month = '' + (d.getMonth() + 1)
let day = '' + d.getDate()
if (month.length < 2) month = '0' + month
if (day.length < 2) day = '0' + day
return [year, month, day].join('-')
}
// 格式化时间
const formatDateTime = (time, second, minute) => {
let result =
time.getFullYear() +
'-' +
(time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1) +
'-' +
(time.getDate() < 10 ? '0' + time.getDate() : time.getDate()) +
' ' +
(time.getHours() < 10 ? '0' + time.getHours() : time.getHours()) +
':'
if (minute === '00' && second === '00') {
result += '00' + ':' + '00'
} else if (second === '00') {
result =
result + (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()) + ':' + '00'
} else {
result =
result +
(time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()) +
':' +
(time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds())
}
return result
}