Created
September 13, 2021 16:58
-
-
Save jaxxreal/ea187c1d15310d32c6f0941406831228 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
function order(sortKey) { | |
return (items) => { | |
return [...items].sort((a, b) => a[sortKey] < b[sortKey] ? 1 : -1); | |
}; | |
} | |
function where(filter) { | |
const [filterKey] = Object.keys(filter); | |
return (items) => | |
items.filter((item) => item[filterKey] === filter[filterKey]); | |
} | |
function query(...transformers) { | |
return (items) => | |
transformers.reduce((acc, transformer) => transformer(acc), items); | |
} | |
test("query", function () { | |
const data = [ | |
{ id: 1, name: "John", surname: "Doe", age: 34 }, | |
{ id: 2, name: "John", surname: "Doe", age: 33 }, | |
{ id: 3, name: "John", surname: "Doe", age: 35 }, | |
{ id: 4, name: "Mike", surname: "Doe", age: 35 } | |
]; | |
const ids = query( | |
where({ name: "John" }), | |
where({ surname: "Doe" }), | |
order("age") | |
)(data).map((u) => u.id); | |
expect(ids).toStrictEqual([3, 1, 2]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment