This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
We will learn how to use the Command design pattern in JavaScript to encapsulate and decouple request processing from request execution.
The Command design pattern is a behavioral pattern that encapsulates a request as an object, allowing us to parameterize clients with different requests, queue or log requests, and support undoable operations. In JavaScript, this pattern can be used to create undo-redo functionality, handle user interface events, and implement a macro recorder. In this lesson we are implementing it by using generators.
const me = {
firstName: 'Krasimir',
lastName: 'Tsonev',
age: 38
}
function commander(user, generator) {
let step, result;
while(step = generator.next(result), !step.done) {
const [ what, param ] = step.value;
if (what === 'get') {
if (param === 'fullname') {
result = `${user.firstName} ${user.lastName}`;
} else if (param === 'age') {
result = user.age;
} else {
throw new Error('Wrong param');
}
} else {
throw new Error('Wrong command');
}
}
}
function * logic() {
const name = yield ['get', 'fullname'];
const age = yield ['get', 'age'];
console.log(name, age);
}
commander(me, logic());
The logic
function is the place where we say what we want and commander
is the place where we define how. We use the async nature of the generators to "pause" our logic.