Skip to content

Instantly share code, notes, and snippets.

@simonschwartz
Last active June 14, 2021 10:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonschwartz/d778e29f35cb0e32bdc804b467664598 to your computer and use it in GitHub Desktop.
Save simonschwartz/d778e29f35cb0e32bdc804b467664598 to your computer and use it in GitHub Desktop.
// given a database of global parcels like this...
const allGlobalParcels = [
{
created: 576424800000,
location: "aus",
properties: { ... },
},
{
created: 1558163267311,
location: "us",
properties: { ... },
},
...2701201201 more items
];
const sortParcelsByCountry = parcels => country => {
// 1. Filter our list to only include parcels from 'country;
const countryParcels = parcels.filter(parcel => parcel.location === country);
// we now return a function that sorts the parcels by date created
return order => {
// 2. Sort the list of packages by date
const sortedResult = [...countryParcels].sort((a, b) => {
if (order === "ascending") return a.created - b.created;
// by default return packages by descending order
return b.created - a.created;
});
return sortedResult;
};
};
// we create a new function with the filtered list of parcels by country in it's closure scope
const sortAusParcelsBy = sortParcelsByCountry(allGlobalParcels)("aus");
const ausParcelsAsc = sortAusParcelsBy("ascending");
const ausParcelsDsc = sortAusParcelsBy("descending");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment