Skip to content

Instantly share code, notes, and snippets.

@emmaly
Last active May 13, 2022 09:18
Show Gist options
  • Save emmaly/1c2b59cbc6cf61c5e04405650e289a97 to your computer and use it in GitHub Desktop.
Save emmaly/1c2b59cbc6cf61c5e04405650e289a97 to your computer and use it in GitHub Desktop.
A way to process an array via map and filter by passing an array of maps and filters
function buildArrayProcessorChain (rawArrayProcessors) {
const arrayProcessors = (typeof rawArrayProcessors !== "object" ? [] :
Array.isArray(rawArrayProcessors) ? rawArrayProcessors : [rawArrayProcessors])
.filter(v => (v.map === undefined && typeof v.filter === "function") || (v.filter === undefined && typeof v.map === "function"));
if (arrayProcessors.length === 0) return (a) => a; // nothing to do
return arrayProcessors.reduceRight((p, c) => {
// filter
if (typeof c.filter === "function") return (a) => typeof p !== "function" ? Array.prototype.filter.call(a, c.filter) : p(Array.prototype.filter.call(a, c.filter));
// map
if (typeof c.map === "function") return (a) => typeof p !== "function" ? Array.prototype.map.call(a, c.map) : p(Array.prototype.map.call(a, c.map));
// invalid item, skipping
return (a) => typeof p !== "function" ? a : p(a);
}, {});
}
function main() {
const a = {
name: "Has City",
filter: (v) => {
Logger.log("City? %s", v.city);
return v?.city?.length > 0;
}
};
const b = {
name: "Under 52",
filter: (v) => {
Logger.log("52> %s", v.age);
return v?.age <52;
}
};
const c = {
name: "Uppercase Names",
map: (v) => {
v.name = v.name.toUpperCase();
Logger.log("BIGNAME %s", v.name);
return v;
}
};
const d = {
name: "No names with upper O",
filter: (v) => {
const remove = v?.name.match(/O/);
Logger.log("Big O is NO %s, %s", v.name, !remove);
return !remove;
}
};
const fns = [a,b,c,d];
const procs = buildArrayProcessorChain(fns);
if (typeof procs === "function") Logger.log(procs([
{
name: "Alice",
age: 40,
city: "Dallas",
},
{
name: "Bob",
age: 52,
city: "Chicago",
},
{
name: "Connie",
age: 28,
city: "Portland",
},
{
name: "Debra",
age: 61,
city: "Seattle",
},
{
name: "Edna",
age: 14,
city: "Salt Lake City",
},
]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment