Created
October 20, 2016 03:48
-
-
Save DroopyTersen/1402f9d602954a2646148a58c52b3c87 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var middlewarify = function(pre, done) { | |
var middleware = []; | |
var func = function(...args) { | |
if (done) middleware.push(done); | |
return middleware.reduce( (chain, fn) => chain.then(fn) | |
, Promise.resolve(pre.apply(null, args))) | |
}; | |
func.use = function(fn){ | |
middleware.push(fn); | |
}; | |
return func; | |
}; | |
var myLibrary = (function() { | |
var authToken = "ABC123"; | |
var getEmployees = function() { | |
// assume api.fetchEmployees makes an AJAX request for a JSON array of employees | |
return api.fetchEmployees(authToken, searchFilter) | |
}; | |
// takes a flat list of employees and returns and array of departments with employees underneath | |
// [ { name: "Finance", employees: [...] }, { name: "IT", employees: [...] }] | |
var groupByDepartment = function(employees) { | |
var deptsObj = employees.reduce((depts, employee) => { | |
if(!depts[employee.department]) depts[employee.department] = []; | |
depts[employee.department].push(employee); | |
}, {}); | |
return Object.keys(deptsObj).map(deptName => { | |
return { | |
name: deptName, | |
employees: deptsObj[deptName] | |
} | |
}); | |
}; | |
return { | |
getDepartments: middlewarify(getEmployees, groupByDepartment) | |
}; | |
})(); | |
// Set empty 'department' to "Unknown" before the employees get grouped by department | |
var handleNullDepartment = function(employees) { | |
employees.forEach(e => e.department = e.department || "Unknown"); | |
return employees; | |
} | |
// Consumers would then use your public, middlewarified method like so: | |
myLibrary.getDepartments.use(handleNullDepartment); | |
myLibrary.getDepartments().then(departments => { | |
console.log("Done") | |
console.log(departments); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment