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関数ドリル】を毎日やる【勉強用】その4

Posted at

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

takeRight関数の挙動
_.takeRight([1, 2, 3]);
// => [3]
 
_.takeRight([1, 2, 3], 2);
// => [2, 3]
 
_.takeRight([1, 2, 3], 5);
// => [1, 2, 3]
 
_.takeRight([1, 2, 3], 0);
// => []

配列から第2引数分だけ末尾から抽出する。第2引数がない場合は末尾を、0の時は空配列を出力する。
##takeRight関数の課題内容

##takeRight関数に取り組む前の状態

  • 引数なしのパターンに応じるにはif,elseを使えばよさそう
  • 少し検索すればできそう

##takeRight関数に取り組んだ後の状態

  • ifの柔軟な使い方が理解できた
  • returnの位置などの理解がまだまだ足りないと感じた
  • 解答コードのような発想は全く思い付かなかった
  • 検索せずに取り組んでみた時は、全く見当違いのことをやっていた

##takeRight関数の実装コード

const takeRight = (array, num) => {
    let newArray = [];
    if (num === 0) {
        return newArray;
    }
    if (num > 1) {
        const popNumber = num;
        newArray = array.slice(-popNumber);
    } else {
        newArray = array.slice(-1);
    }
    return newArray;
};

console.log(takeRight([1, 2, 3, 4, 5, 6], 3));
//[4,5,6]
console.log(takeRight([1, 2, 3, 4, 5, 6]));
//[6]
console.log(takeRight([1, 2, 3, 4, 5, 6], 8));
//[1,2,3,4,5,6]
console.log(takeRight([1, 2, 3, 4, 5, 6], 0));
//[]

##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?