Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created November 27, 2021 15:21
Show Gist options
  • Save fostyfost/2a2aa0c0117deceea635cf6d572a2396 to your computer and use it in GitHub Desktop.
Save fostyfost/2a2aa0c0117deceea635cf6d572a2396 to your computer and use it in GitHub Desktop.
Items of array are unique in order
import { uniqueInOrder } from './unique-in-order'
const obj1 = { id: '1' }
const obj2 = { id: '2' }
const obj3 = { id: '3' }
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [7, 8, 9]
test('`uniqueInOrder` should work correctly', () => {
expect(uniqueInOrder([])).toBe(true)
expect(uniqueInOrder([1])).toBe(true)
expect(uniqueInOrder(['a'])).toBe(true)
expect(uniqueInOrder([obj1])).toBe(true)
expect(uniqueInOrder([arr1])).toBe(true)
expect(uniqueInOrder([1, 2, 3])).toBe(true)
expect(uniqueInOrder(['a', 'b', 'c'])).toBe(true)
expect(uniqueInOrder([obj1, obj2, obj3])).toBe(true)
expect(uniqueInOrder([arr1, arr2, arr3])).toBe(true)
expect(uniqueInOrder([1, 2, 2, 3])).toBe(false)
expect(uniqueInOrder(['a', 'b', 'b', 'c'])).toBe(false)
expect(uniqueInOrder([obj1, obj2, obj2, obj3])).toBe(false)
expect(uniqueInOrder([arr1, arr2, arr2, arr3])).toBe(false)
})
/**
* Checks that there are no consecutive repeated elements in the array, for example:
* ['a', 'b', 'c', 'd'] -> TRUE
* ['b', 'b', 'C', 'C', 'd'] -> FALSE
*/
export const uniqueInOrder = <T = unknown>(arr: T[]): boolean => {
return arr.every((item, index) => item !== arr[index + 1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment