LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript関数ドリル】中級編のchunk関数の実装アウトプット

Posted at

chunk関数の課題内容

_.chunk関数を自分で実装する課題。
https://lodash.com/docs/4.17.15#chunk

「課題内容」/「解説動画」/「解答例」を確認したい場合は、以下リンク先のページを参照。
https://js-drills.com/blog/chunk/

課題に取り組む前の状態

  • 解答例を見なくてもできそうと思った。

課題に取り組んだ後の状態

  • 解答例では第二引数が想定通りでない場合の処理を記述していたので、勉強になった。
  • 解答例ではWhile文とsplice関数を使用してシンプルに記述されているので、こういった記述ができるように参考にしたい。

chunk関数の実装コード(答えを見る前)

function chunk(array, size = 1) {
  const chunkArray = [];
  let tempArray = [];
  let currentLen = 0;

  for (let i = 0; i < array.length; i++) {
    if (currentLen < size) {
      tempArray.push(array[i]);
      currentLen++;
    } else {
      chunkArray.push(tempArray);
      currentLen = 0;
      tempArray = [];
      tempArray.push(array[i]);
    }
    if (i == array.length - 1) {
      chunkArray.push(tempArray);
    }
  }
  return chunkArray;
}

console.log(chunk(["a", "b", "c", "d"], 2));
// => [['a', 'b'], ['c', 'd']]

console.log(chunk(["a", "b", "c", "d"], 3));
// => [['a', 'b', 'c'], ['d']]

chunk関数の実装コード(答えを見た後)

function chunk(array, size = 1) {
    const copiedArray = [...array];
    const chunkedArray = [];

    if (size < 1) {
        throw new Error("Please choose a number greater than 0");
    }

    while (copiedArray.length > 0) {
        chunkedArray.push(copiedArray.splice(0, size))
    }

    return chunkedArray;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0