Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save KristofferK/dcf6e6776c8272b70e30c2835d3f6a0d to your computer and use it in GitHub Desktop.

Select an option

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
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