Skip to content

Instantly share code, notes, and snippets.

@jaxxreal
Created September 13, 2021 16:58
Show Gist options
  • Save jaxxreal/ea187c1d15310d32c6f0941406831228 to your computer and use it in GitHub Desktop.
Save jaxxreal/ea187c1d15310d32c6f0941406831228 to your computer and use it in GitHub Desktop.
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