💾arr.containsSubarray()
Last updated
Last updated
💡 祕技:下面的 valueIsInArraySequentially
用了一個內含參數 i
的 closure,讓每次測試「一個值是否在陣列中」,都從新的位置開始搜尋:
// ⭐️ 注意:函數的參數都是變數(var)
// intial value of `i` = 0  ̄ ̄ ̄ ̄ ̄ ̄⤵︎
(i => v => i = this.indexOf(v, i) + 1)(0)
簡直是太聰明了👍
// 🔸 arr.containsSubarray()
Array.prototype.containsSubarray = function(subarray, orderIsRelevant=false) {
// ⭐ closure with internal parameter `i`
const valueIsInArraySequentially = (i => v => i = this.indexOf(v, i) + 1)(0);
const valueIsInArray = (v => this.includes(v));
const valuePassedTest = orderIsRelevant ? valueIsInArraySequentially : valueIsInArray;
return subarray.every(valuePassedTest);
};
valueIsInArraySequentially is equivalent to:
// closure (with internal variable `startFromIndex`)
const valueInArraySequentially = (()=>{
// internal variable in clusure
let startFromIndex = 0;
// when calling `array.containsSubarray()`, `this === array`
return (value) => startFromIndex = this.indexOf(value, startFromIndex) + 1;
})();
💈範例:
⭐️ 注意:
當 orderIsRelevant
參數設為 false
(預設值),重複的值(如下面第三例)不管重複幾次,都會被當作有在陣列中(valueIsInArray
),依然會傳回 true
❗️
// test array
const array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
[
// order is relevant: NO | YES
// -----------------------------------
[777, 22, 22], // true | true
[777, 22, 3], // true | true
[77, 77], // true | false (true when order is irrelevant❗duplicate values neglected)
[22, 44], // true | false (false when order is relevant ⭐)
].forEach(arr =>
console.log(
array.containsSubarray(arr), // order is irrelevant
array.containsSubarray(arr, true) // order IS relevant
)
)
arrow function doesn't have its own this
.