Last active
February 11, 2018 00:27
-
-
Save KristofferK/dcf6e6776c8272b70e30c2835d3f6a0d to your computer and use it in GitHub Desktop.
Checks if a given array has multiple items of the same data type next to each other. In the test code it checks if a given array has three numbers cohesively. Using reducer and only one line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const array1 = [1,2,'a',3,'b',4,5] | |
| const array2 = [1,2,'a',3,'b',4,5,6,'k'] | |
| const checkIfArrayHasNValuesOfSameDataTypeCohesively = datatype => n => array => (array.reduce((acc, val) => ( | |
| {passed: acc.passed || (acc.n = typeof val != datatype ? 0 : acc.n + 1) >= n, n: acc.n} | |
| ), {n: 0, passed: false})).passed; | |
| const hasThreeNumbersCohesively = checkIfArrayHasNValuesOfSameDataTypeCohesively('number')(3); | |
| console.log(hasThreeNumbersCohesively(array1)); // false | |
| console.log(hasThreeNumbersCohesively(array2)); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment