Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This code creates a self-invoking function that simulates an abstract class named `Math`
- that has all the main 4 operations in math. This "class" can be called like an abstract
- class, without the need of creating an instance with the `new` keyword.
- Example:
- ```javascript
- Math.add(1,2);
- // output: 3
- ```
- */
- const Math = (function() {
- const add = (a,b) => a+b;
- const sub = (a,b) => a-b;
- const multiplies = (a,b) => a*b;
- const divides = (a,b) => a/b;
- return {
- add,
- sub,
- multiplies,
- divides
- }
- })();
- /*
- This is the same as above but simulates an interface, exposing all the `Math` class
- methods adding a different behaviour when a global toggle value `DEBUG` is set to
- `true`.
- Example:
- ```javascript
- IMath.add(1,2)
- // output for DEBUG = true: Result is 3
- // output for DEBUG = FALSE: 3
- */
- const IMath = (function () {
- const _printResult = (func, ...params) => {
- return DEBUG ? console.log(`Result is ${func(...params)}`) : func(...params);
- }
- return {
- add: (...params) => _printResult(Math.add, ...params),
- sub: (...params) => _printResult(Math.sub, ...params),
- multiplies: (...params) => _printResult(Math.multiplies, ...params),
- divides: (...params) => _printResult(Math.divides, ...params)
- }
- })();
- /*
- This allows to create clean classes and different interfaces that use them
- for different contexts.
- */
- const DEBUG = true;
- IMath.multiplies(10,20);
- console.log(`What i'm saying is that 10 times 20 is ${Math.multiplies(10,20)}`);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement