0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

takeRight関数の課題内容

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

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

課題に取り組む前の状態

  • 配列関数のslice()を使えばいいのかなと思った
  • slice()の動きがうろ覚え

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

  • slice()の動きをリファレンスで確認して実装した
  • Returns the slice of array という要件の部分で、リファレンスではslice()は新しい配列を返すとあったので、解答例のように新しい配列の宣言をせず、そのまま返り値を戻したがよかったのか確信なし。

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

function takeRight(arr, n = 1) {

    if (n >= arr.length) {
        return arr;
    }

    if (n === 0) {
        return [];
    }

    return arr.slice(-n);
}


takeRight関数の実装コード(解答例)

function takeRight(array, n = 1) {
  if(n === 0) {
    return [];
  }
  if(n > array.length) {
    return [...array];
  }

  const takenArray = [];
  for(let i = 0; i < n; i++) {
    // array [1, 2, 3]
    // 1 + i => 1, 2, 3
    // array.length =>
    //   3 - (1 + 0) = 2,
    //   3 - (1 + 1) = 1
    //   3 - (1 + 2) = 0
    const indexFromRight = array.length - (1 + i)
    takenArray.unshift( array[indexFromRight] );
  }

  return takenArray;
}

console.log( takeRight([1, 2, 3]) );
// => [3]

console.log( takeRight([1, 2, 3], 2) );
// => [2, 3]

console.log( takeRight([1, 2, 3], 5) );
// => [1, 2, 3]

console.log( takeRight([1, 2, 3], 0) ) ;
// => []
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?