[Easy] 手寫 dropRightWhile

2024年1月28日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

題目描述

Lodash 的 dropRightWhile 是開發中經常被用的效用函式,也經常會在面試被問到。 dropRightWhile 會從陣列的末端開始,移除符合指定條件的元素,直到遇到不符合條件的元素為止,並回傳剩餘的元素所組成的新陣列。同時確保原始陣列保持不變

dropRightWhile(
  ["hello", "world", "today", "isGood"],
  (value) => value.length > 5
); // =>  ['hello', 'world', 'today']
dropRightWhile(
  [
    { name: "Alice", age: 25 },
    { name: "Charlie", age: 20 },
    { name: "Bob", age: 30 },
  ],
  (obj) => obj.age > 25
); // => [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 20 }]
dropRightWhile([10, 20, 30, 40, 50, 10], (value) => value !== 10); // => [10, 20, 30, 40, 50, 10]
dropRightWhile([1], (value) => value > 0); // => []

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 成長計畫看到

解法一

function dropRightWhile(array, predicate) {
  let index = array.length - 1;

  while (index >= 0 && predicate(array[index], index, array)) {
    index--;
  }

  return array.slice(0, index + 1);
}

解法二

function dropRightWhile(array, predicate) {
  for (let i = array.length - 1; i >= 0; i--) {
    if (!predicate(array[i], i, array)) {
      return array.slice(0, i + 1); // Return as soon as predicate is false
    }
  }
  return []; // If all elements meet the predicate, return an empty array
}
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們