d8c593c2105470fc515dfeca85fe11250e5af3d0.svn-base 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. define(function (){
  2. function kwargs(func, defaults) {
  3. /*jshint maxlen : 200*/
  4. var removeComments = new RegExp('(\\/\\*[\\w\\\'\\,\\(\\)\\s\\r\\n\\*]*\\*\\/)|(\\/\\/[\\w\\s\\\'][^\\n\\r]*$)|(<![\\-\\-\\s\\w\\>\\/]*>)', 'gim');
  5. var removeWhitespc = new RegExp('\\s+', 'gim');
  6. var matchSignature = new RegExp('function.*?\\((.*?)\\)', 'i');
  7. // get the argument names from function source
  8. var names = func.toString()
  9. .replace(removeComments, '')
  10. .replace(removeWhitespc, '')
  11. .match(matchSignature)[1]
  12. .split(',');
  13. // Check the existance of default, if not create an object
  14. if(defaults !== Object(defaults)){
  15. defaults = {};
  16. }
  17. return function () {
  18. var args = Array.prototype.slice.call(arguments);
  19. var kwargs = args[args.length - 1];
  20. // Check the existance of the kwargs
  21. if (kwargs && kwargs.constructor === Object) {
  22. args.pop();
  23. }
  24. else{
  25. kwargs = {};
  26. }
  27. // Fill the arguments and apply them
  28. for (var i = 0; i < names.length; i++) {
  29. var name = names[i];
  30. if (name in kwargs) {
  31. args[i] = kwargs[name];
  32. }
  33. else if(name in defaults && args[i] == null){
  34. args[i] = defaults[name];
  35. }
  36. }
  37. return func.apply(this, args);
  38. };
  39. }
  40. // As function prototype
  41. // Function.prototype.kwargs = kwargs;
  42. return kwargs;
  43. });