diff --git a/README.md b/README.md index 5c51180bd..ef387092b 100644 --- a/README.md +++ b/README.md @@ -1603,10 +1603,12 @@ Return `0` if the `direction` changes or the `direction` if the last element is ```js const isSorted = arr => { - const direction = arr[0] > arr[1] ? -1 : 1; - for (let [i, val] of arr.entries()) - if (i === arr.length - 1) return direction; + let direction = -(arr[0] - arr[1]); + for (let [i, val] of arr.entries()) { + direction = !direction ? -(arr[i - 1] - arr[i]) : direction; + if (i === arr.length - 1) return !direction ? 0 : direction; else if ((val - arr[i + 1]) * direction > 0) return 0; + } }; ``` diff --git a/docs/index.html b/docs/index.html index 02031c09e..7d560d6c5 100644 --- a/docs/index.html +++ b/docs/index.html @@ -278,10 +278,12 @@ Object.assig

intersectionWith

Returns a list of elements that exist in both arrays, using a provided comparator function.

Use Array.filter() and Array.findIndex() in combination with the provided comparator to determine intersecting values.

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
 
intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
 

isSorted

Returns 1 if the array is sorted in ascending order, -1 if it is sorted in descending order or 0 if it is not sorted.

Calculate the ordering direction for the first two elements. Use Object.entries() to loop over array objects and compare them in pairs. Return 0 if the direction changes or the direction if the last element is reached.

const isSorted = arr => {
-  const direction = arr[0] > arr[1] ? -1 : 1;
-  for (let [i, val] of arr.entries())
-    if (i === arr.length - 1) return direction;
+  let direction = -(arr[0] - arr[1]);
+  for (let [i, val] of arr.entries()) {
+    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
+    if (i === arr.length - 1) return !direction ? 0 : direction;
     else if ((val - arr[i + 1]) * direction > 0) return 0;
+  }
 };
 
isSorted([0, 1, 2, 2]); // 1
 isSorted([4, 3, 2]); // -1
diff --git a/snippets/isSorted.md b/snippets/isSorted.md
index 13842e285..b5ece6291 100644
--- a/snippets/isSorted.md
+++ b/snippets/isSorted.md
@@ -8,12 +8,12 @@ Return `0` if the `direction` changes or the `direction` if the last element is
 
 ```js
 const isSorted = arr => {
-	let direction = -(arr[0] - arr[1]);
-	for (let [i, val] of arr.entries()) {
-		direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
-		if (i === arr.length - 1) return !direction ? 0 : direction;
-		else if ((val - arr[i + 1]) * direction > 0) return 0;
-	}
+  let direction = -(arr[0] - arr[1]);
+  for (let [i, val] of arr.entries()) {
+    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
+    if (i === arr.length - 1) return !direction ? 0 : direction;
+    else if ((val - arr[i + 1]) * direction > 0) return 0;
+  }
 };
 ```