Skip to content

Instantly share code, notes, and snippets.

@MHerszak
Last active November 21, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MHerszak/c7f723589c17f2e00d22feb6fa976baa to your computer and use it in GitHub Desktop.
Save MHerszak/c7f723589c17f2e00d22feb6fa976baa to your computer and use it in GitHub Desktop.
Build a SOLID strategy in Javascript
/**
* Command Interface
* @param {*} state
*/
const CommandI = (state) => ({
type: 'CommandI',
execute: (...rest) => state.execute(...rest),
});
/**
* Receiver Interface
* @param {*} state
*/
const ReceiverI = (state) => ({
type: 'ReceiverI',
process: (...rest) => state.process(...rest),
});
/**
*
* @param {*} receiver
*/
function OnCommand(receiver) {
// Prepare proto
const proto = {
type: 'OnCommand',
// Execute add addition method
execute(...rest) {
return receiver.process(...rest);
}
};
// Add
const basics = CommandI(proto);
// Greate object and return functions
return Object.freeze(
Object.create(basics)
);
}
function Invoker(command) {
// Prepare proto
const proto = {
type: 'Invoker',
// Execute add addition method
execute(...rest) {
return command.execute(...rest);
}
};
// Add
const basics = CommandI(proto);
// Greate object and return functions
return Object.freeze(
Object.create(basics)
);
}
function Addition() {
// Prepare proto
const proto = {
type: 'Addition',
// Execute add addition method
process(a, b) {
return parseInt(a) + parseInt(b);
}
};
// Add
const basics = ReceiverI(proto);
// Greate object and return functions
return Object.freeze(
Object.create(basics)
);
}
function Subtraction() {
// Prepare proto for specific implementation
const proto = {
type: 'Subtraction',
// Execute add addition method
process(a, b) {
return parseInt(a) - parseInt(b);
}
};
// Subtraction
const basics = ReceiverI(proto);
// Greate object and return functions
return Object.freeze(
Object.create(basics)
);
}
function CalculatorContext(strategy) {
function executeStrategy(...rest) {
return strategy.execute(...rest);
}
return Object.freeze(
Object.create({
execute: executeStrategy
})
);
}
const additionCommand = OnCommand(
Addition()
);
const subCommand = OnCommand(
Subtraction()
);
const addition = CalculatorContext(
additionCommand
);
const subtraction = CalculatorContext(
subCommand
);
const add = Invoker(addition);
const sub = Invoker(subtraction);
const resultAdd = add.execute(3,4);
const resultSub = sub.execute(3,4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment