Created
July 22, 2019 10:41
-
-
Save lloydjatkinson/3b83e976d483075cf60ecc6d31f94133 to your computer and use it in GitHub Desktop.
This file contains 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
export const filterCollection = <TOriginal>(originalCollection: TOriginal[], search: (item: TOriginal) => boolean) => { | |
const result = originalCollection.filter(search); | |
return { | |
anyMatches: result.length > 0, | |
originalCollection, | |
filteredCollection: result | |
}; | |
}; | |
import { filterCollection } from './filter-collection'; | |
describe('Primitive types', () => { | |
test('should return the original collection of numbers', () => { | |
const original = [1, 2, 3, 4, 5]; | |
const result = filterCollection<number>(original, (item => false)); | |
expect(result.originalCollection).toEqual(original); | |
}); | |
test('should return no number results with a noop search function', () => { | |
const result = filterCollection<number>([1, 2, 3, 4, 5], (item => false)); | |
expect(result.anyMatches).toBe(false); | |
expect(result.filteredCollection).toHaveLength(0); | |
}); | |
test('should return with two matching numbers', () => { | |
const result = filterCollection<number>([1, 2, 3, 4, 5], (item => item % 2 === 0)); | |
expect(result.anyMatches).toBe(true); | |
expect(result.filteredCollection).toHaveLength(2); | |
}); | |
}); | |
describe('Objects', () => { | |
interface Customer { | |
name: string, | |
getsDiscount: boolean, | |
}; | |
const customers: Customer[] = [ | |
{ name: 'Lloyd 1', getsDiscount: true }, | |
{ name: 'Bob', getsDiscount: false }, | |
{ name: 'Tom', getsDiscount: true }, | |
{ name: 'Tim', getsDiscount: false }, | |
]; | |
test('should return the original collection of customers', () => { | |
const result = filterCollection<Customer>(customers, (item => false)); | |
expect(result.originalCollection).toEqual(customers); | |
}); | |
test('should return no customer results with a noop search function', () => { | |
const result = filterCollection<Customer>(customers, (item => false)); | |
expect(result.anyMatches).toBe(false); | |
expect(result.filteredCollection).toHaveLength(0); | |
}); | |
test('should return customers with discount', () => { | |
const result = filterCollection<Customer>(customers, (item => item.getsDiscount)); | |
expect(result.anyMatches).toBe(true); | |
expect(result.filteredCollection).toHaveLength(2); | |
expect(result.filteredCollection).toContainEqual(customers[0]); | |
expect(result.filteredCollection).toContainEqual(customers[2]); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment