Guest User

Untitled

a guest
Feb 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. // Converts any function to accept continuation-passing style
  2. //
  3. // var add = function(a, b) {
  4. // return a + b;
  5. // };
  6. //
  7. // var addcps = add.toCPS();
  8. //
  9. // addcps(3, 4, function(x) { alert(x) });
  10.  
  11. Function.prototype.toCPS = function() {
  12. var direct = this;
  13. return function() {
  14. var args = [], i = arguments.length,
  15. cps, context, result;
  16.  
  17. while (i--) args[i] = arguments[i]; // (1)
  18.  
  19. context = (args[args.length-2] instanceof Function)
  20. ? args.pop() : null; // (2)
  21.  
  22. cps = args.pop();
  23. result = direct.apply(this, args); // (3)
  24. cps.call(context, result);
  25. };
  26. };
Add Comment
Please, Sign In to add comment