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関数ドリル】中級編の dropRightWhile関数の実装アウトプット

Last updated at Posted at 2022-06-12

dropRightWhile 関数の課題内容

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

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

課題に取り組む前の状態

  • 関数の説明文と例を見たところ、第二引数が関数の場合とそうでない場合があり、解答を見ないと分からないと思った。

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

  • 動画の最初の説明で、今回は第二引数は関数の場合だけを想定して実装するとあったので、そこで動画視聴は一旦中断して、自分で実装を試みた。なんとか、サンプルの処理結果と同じように処理できるものができた。
  • breakを使用するのを忘れたため、今後気をつけたい。

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

function dropRightWhile(array, predicate) {
  const newArray = [...array];
  for (let i = array.length - 1; i >= 0; i--) {
    // console.log(newArray[i]);

      if (predicate(newArray[i])) {
          newArray.pop();
      } else {
          return newArray;
      }
  }
  return newArray;
}

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

function dropRightWhile(array, predicate) {
  const newArray = [...array];
  for (let i = array.length - 1; i >= 0; i--) {
    // console.log(newArray[i]);

    if (!predicate(newArray[i])) {
      break;
    }
    newArray.pop();
  }
  return newArray;
}

var users = [
  { user: "barney", active: true },
  { user: "fred", active: false },
  { user: "pebbles", active: false },
];
console.log(
  dropRightWhile(users, function (o) {
    return !o.active;
  })
);
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?