Guest User

Untitled

a guest
Dec 14th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. type MethodDecorator = (target: any, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) =>
  2. TypedPropertyDescriptor | void;
  3.  
  4. type AssertFn = (...args: Array<any>) => void;
  5.  
  6. class TSContract {
  7. private static isCustomContractInterruptionCb: boolean = false;
  8.  
  9. private static contractInterruptionCb(message: string): void {
  10. console.warn(message);
  11. }
  12.  
  13. static setupContractInterruptionCb(cb: (message: string) => void): void {
  14. if (TSContract.isCustomContractInterruptionCb) {
  15. console.warn('Custom contract interruption callback already setted, break');
  16. return;
  17. }
  18. TSContract.contractInterruptionCb = cb;
  19. TSContract.isCustomContractInterruptionCb = true;
  20. }
  21.  
  22. static assert(expression: boolean, errorMessage: string): void {
  23. if (!expression) {
  24. TSContract.contractInterruptionCb(errorMessage);
  25. }
  26. }
  27.  
  28. static In(assertFn: AssertFn): MethodDecorator {
  29. return function(target: any, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor {
  30. const originalValue = descriptor.value;
  31. function newValue(...args) {
  32. assertFn(...args);
  33. return originalValue.apply(this, args);
  34. }
  35. descriptor.value = newValue;
  36. return descriptor;
  37. };
  38. }
  39.  
  40. static Out(assertFn: AssertFn): MethodDecorator {
  41. return function(target: any, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor {
  42. const originalValue = descriptor.value;
  43. function newValue(...args) {
  44. result = originalValue.apply(this, args);
  45. assertFn(result);
  46. return result;
  47. }
  48. descriptor.value = newValue;
  49. return descriptor;
  50. };
  51. }
  52. }
  53.  
  54. class ContractTest {
  55. @TSContract.In(a => {
  56. TSContract.assert(typeof a === 'number', 'Not a number!');
  57. })
  58. @TSContract.Out(retVal => {
  59. TSContract.assert(!retVal, 'Wat?! Return?!');
  60. })
  61. doSome(a: number, withReturn: boolean = false): void {
  62. console.log(a);
  63. if (withReturn) {
  64. return a;
  65. }
  66. }
  67. }
  68.  
  69. TSContract.setupContractInterruptionCb((message: string) => {
  70. console.error(message);
  71. });
  72.  
  73. // cant setup another callback
  74. TSContract.setupContractInterruptionCb((message: string) => {
  75. console.error(message);
  76. });
  77.  
  78. const ct = new ContractTest();
  79. ct.doSome(12);
  80. ct.doSome('12');
  81. ct.doSome(12, true);
Add Comment
Please, Sign In to add comment