allEqual
The allEqual
function is a utility function that checks if all elements in an array are equal. It is generic, meaning it can handle arrays of any type.
#
Function Signatureconst allEqual = <T>(arr: T[]) => boolean;
#
Parametersarr: T[]
: An array of type T
, where T
can be any type (e.g., number, string, boolean, etc.).
#
Returnsboolean
: The function returns true
if all elements in the array are equal, and false
otherwise. If the array is empty, it returns false
.
#
Examples#
Example 1: Array of Numbersconst result = allEqual([1, 1, 1, 1]); console.log(result); // Output: true
#
Example 2: Array of Stringsconst result = allEqual(['a', 'a', 'a']); console.log(result); // Output: true
#
Example 3: Array with Mixed Valuesconst result = allEqual([1, 2, 3, 1]); console.log(result); // Output: false
#
Example 4: Empty Arrayconst result = allEqual([]); console.log(result); // Output: false
#
How It WorksThe function first checks if the array is empty using
arr.length === 0
. If it is, the function returnsfalse
.If the array is not empty, it uses the
every
method to check if every element in the array is strictly equal (===
) to the first elementarr[0]
.If all elements match, it returns
true
. If any element is different, it returnsfalse
.