跳至主要內容

09.手写lodash里的函数

pinia大约 2 分钟

01.手写 chunk 里的函数

/**
 * 将一个数组分割成多个 size 长度的区块,每个区块组成小数组。
 * 如果数组无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。
 * @param {Array} array 需要处理的数组
 * @param {Number} size 每个数组区块的长度
 * @returns {Array} 返回一个包含拆分区块的新数组(相当于一个二维数组)。
 * @example
 * chunk(['a', 'b', 'c', 'd'], 2);
 * // => [['a', 'b'], ['c', 'd']]
 *
 * chunk(['a', 'b', 'c', 'd'], 3);
 * // => [['a', 'b', 'c'], ['d']]
 */

const chunk = (array, size = 1) => {
	if (size < 1) return [];
	const result = [];
	for (let i = 0; i < array.length; i += size) {
		result.push(array.slice(i, i + size));
	}
	return result;
};
console.log(chunk(["a", "b", "c", "d", "e"], 2));

02.手写 countBy 函数

/**
 * 通过传入的iteratee函数对collection中的每个元素进行分组
 * 其得到的结果作为返回对象的键
 * 返回对象的每个键对应一个数字,用于统计该键出现的次数
 * iteratee函数接受一个参数value,该参数表示collection中的某个元素
 * @param {Array/Object} collection
 * @param {Function} iteratee
 * @returns {Object}
 * @example
 * const users = [
 * { 'user': 'barney', 'active': true },
 * { 'user': 'fred', 'active': false },
 * { 'user': 'pebbles', 'active': false }
 * ]
 * countBy(users, value => value.active)
 * // => { 'true': 1, 'false': 2 }
 */
const countBy = (collection, iteratee) => {
	const result = {};
	for (const item of collection) {
		const key = iteratee(item);
		result[key] ? result[key]++ : (result[key] = 1);
	}
	return result;
};
const fun = (value) => value.active;
const res = countBy(
	[
		{ user: "barney", active: true },
		{ user: "fred", active: false },
		{ user: "pebbles", active: false },
	],
	fun
);
console.log(res);

03.手写 get 函数

/**
 * 手写lodash里的get方法
 * @param {Object} object
 * @param {String/Array} path
 * @param {*} defaultValue
 * @returns
 * @example
 * const obj = { a: { b: { c: 1 } } }
 * get(obj, 'a.b.c') // 1
 * get(obj, 'a.b.c.d') // undefined
 * get(obj, 'a.b.c.d', 10) // 10
 */

const get = (object, path, defaultValue) => {
	let obj = object;
	// if (typeof path === 'string') path = path.split('.')
	if (typeof path === "string") path = path.match(/[^\[\].]+/g);
	for (const key of path) {
		if (!obj) return defaultValue;
		obj = obj[key];
	}
	return obj === undefined ? defaultValue : obj;
};
console.log(get({ a: { b: { c: 1 } } }, "a.b.c"));

04.手写 memoize 函数

function memoize(func, resolver) {
	const memoized = function (...args) {
		const key = resolver ? resolver.apply(this, ...args) : args[0];
		if (memoized.cache.has(key)) {
			return memoized.cache.get(key);
		} else {
			const res = func.apply(this, args);
			memoized.cache.set(key, res);
			return res;
		}
	};
	//函数缓存
	memoized.cache = new WeakMap();
	return memoized;
}
上次编辑于:
贡献者: 林深不见鹿