js 手写 深拷贝, 数据扁平化, 柯里化

1. 深拷贝

let arr = [1, [{name: '张三'}, [18, 22], undefined], null, 'hello']
function deepClone(target) {
	let result;
	if (typeof target === 'object') {
		if (Array.isArray(target)) {
			result = []
			for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
		} else if (target === null) { // null的情况
			result = target
		} else if (target.constructor === RegExp) { // 正则的情况
			result = target
		} else {
			result = {}
			for (let key in target) {
				result[key] = deepClone(target[key])
			}
		}
	} else {
		result = target
	}
	return result
}
console.log(deepClone(arr))

2. 数组降维(扁平化数据)

function flatAll(arr) {
     let result = [];
     arr.forEach(item => {
     	if (Array.isArray(item)) {
            result = result.concat(arguments.callee(item)) // arguments.callee递归
        } else {
            result.push(item)
         }
     })
 	 return result
}
 console.log(flatAll([1,[2,2,[3,3,[4,4,[5,5,[6,6,[7,7]]]]]]]));
 // [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]

3. 柯里化 add(1)(2)(3)

const curry = (fn, ...args) => {
	// 函数的参数个数可以直接通过函数数的.length属性来访问
	// 传入的参数大于等于原始函数fn的参数个数,则直接执行该函数
	return args.length >= fn.length 
		? fn(...args) : 
	/**
     * 传入的参数小于原始函数fn的参数个数时
     * 则继续对当前函数进行柯里化,返回一个接受所有参数(当前参数和剩余参数)
     * 的函数
    */
		(..._args) => curry(fn, ...args, ..._args)
}

function add1 (a, b, c) {
	return a + b + c
}
const add = curry(add1)
console.log(add(1)(2)(3)) // 6
console.log(add(1, 2)(3)) // 6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值