Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. /*
  2. This code creates a self-invoking function that simulates an abstract class named `Math`
  3. that has all the main 4 operations in math. This "class" can be called like an abstract
  4. class, without the need of creating an instance with the `new` keyword.
  5.  
  6. Example:
  7. ```javascript
  8. Math.add(1,2);
  9. // output: 3
  10. ```
  11. */
  12. const Math = (function() {
  13.  
  14. const add = (a,b) => a+b;
  15. const sub = (a,b) => a-b;
  16. const multiplies = (a,b) => a*b;
  17. const divides = (a,b) => a/b;
  18.  
  19. return {
  20. add,
  21. sub,
  22. multiplies,
  23. divides
  24. }
  25. })();
  26.  
  27. /*
  28. This is the same as above but simulates an interface, exposing all the `Math` class
  29. methods adding a different behaviour when a global toggle value `DEBUG` is set to
  30. `true`.
  31.  
  32. Example:
  33. ```javascript
  34. IMath.add(1,2)
  35. // output for DEBUG = true: Result is 3
  36. // output for DEBUG = FALSE: 3
  37. */
  38. const IMath = (function () {
  39. const _printResult = (func, ...params) => {
  40. return DEBUG ? console.log(`Result is ${func(...params)}`) : func(...params);
  41. }
  42.  
  43. return {
  44. add: (...params) => _printResult(Math.add, ...params),
  45. sub: (...params) => _printResult(Math.sub, ...params),
  46. multiplies: (...params) => _printResult(Math.multiplies, ...params),
  47. divides: (...params) => _printResult(Math.divides, ...params)
  48. }
  49. })();
  50.  
  51. /*
  52. This allows to create clean classes and different interfaces that use them
  53. for different contexts.
  54. */
  55. const DEBUG = true;
  56. IMath.multiplies(10,20);
  57. 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