Overview
Implement createPipeline(middlewares) that returns an async function processing a context through each middleware sequentially.
Each middleware has the signature (ctx, next) => {} — must call next() to continue.
Examples
const pipeline = createPipeline([
async (ctx, next) => { ctx.x = 1; await next(); },
async (ctx, next) => { ctx.y = 2; await next(); },
]);
const ctx = {};
await pipeline(ctx); // ctx = { x: 1, y: 2 }Solution
Reveal solution
function createPipeline(middlewares) {
return async function(ctx) {
let index = 0;
async function next() {
if (index < middlewares.length) {
const mw = middlewares[index++];
await mw(ctx, next);
}
}
await next();
return ctx;
};
}middleware-pipeline.js
Middleware Pipeline
mediumcodingJavaScriptDesign Patterns
Overview
Implement createPipeline(middlewares) that returns an async function processing a context through each middleware sequentially.
Each middleware has the signature (ctx, next) => {} — must call next() to continue.
Examples
const pipeline = createPipeline([
async (ctx, next) => { ctx.x = 1; await next(); },
async (ctx, next) => { ctx.y = 2; await next(); },
]);
const ctx = {};
await pipeline(ctx); // ctx = { x: 1, y: 2 }Solution
Reveal solution
function createPipeline(middlewares) {
return async function(ctx) {
let index = 0;
async function next() {
if (index < middlewares.length) {
const mw = middlewares[index++];
await mw(ctx, next);
}
}
await next();
return ctx;
};
}NameTopicDifficulty
103 of 103 problems