From 82abddab67d18a6da4c225af7e8abdc280620286 Mon Sep 17 00:00:00 2001 From: xuwu Date: Thu, 25 Mar 2021 08:04:50 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E7=AC=AC=E5=85=AD=E9=A2=98=E7=AD=94?= =?UTF-8?q?=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Answer/1 ~ 10/6.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Answer/1 ~ 10/6.md diff --git a/Answer/1 ~ 10/6.md b/Answer/1 ~ 10/6.md new file mode 100644 index 0000000..c395449 --- /dev/null +++ b/Answer/1 ~ 10/6.md @@ -0,0 +1,70 @@ +```js +/** + * @param input + * @param size + * @returns {Array} + */ +_.chunk(['a', 'b', 'c', 'd'], 2) +// => [['a', 'b'], ['c', 'd']] + +_.chunk(['a', 'b', 'c', 'd'], 3) +// => [['a', 'b', 'c'], ['d']] + +_.chunk(['a', 'b', 'c', 'd'], 5) +// => [['a', 'b', 'c', 'd']] + +_.chunk(['a', 'b', 'c', 'd'], 0) +// => [] +``` + +这道题目其实就是让大家实现一个 lodash 里的函数,这边我们需要注意的一个点是不能更改原数组,虽然题目没有提到,但是我们得想到这个。 + +笔者这里推荐几个答案,分别是不同的写法,难度从低到高吧。 + +首先是遍历的写法: + +[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799053150) + +```js +function chunk(arr, num) { + if (num === 0) return []; + if (Array.isArray(arr) && typeof num === "number") { + let result = []; + let i = 0; + while (i < arr.length) { + result.push(arr.slice(i, i + num)); + i += num; + } + return result; + } else { + console.log("params type error"); + } +} +``` + +我们也可以使用 `reduce` 来解题: + +[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799021398) + +```js +const chunk = (arr, len) => arr.reduce((pre, cur, index) => { + if (index % len === 0) { + pre.push([cur]) + return pre + } + const temp = pre[pre.length - 1] + temp && temp.push(cur) + return pre +}, []) +``` + +甚至直接优化到一行: + +[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799344324) + +```js +function chunk(arr, size){ + return Array.from({length: (size = Number.parseInt(size)) ? Math.ceil(arr.length/size) : 0}) + .map((a,i) => arr.slice(i*size, (i+1)*size)) +} +```