Guest User

Untitled

a guest
Jun 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. function typeDecorator(func, arr) {
  2. if (arguments.length > 2) {
  3. arr = [].slice.call(arguments, 1);
  4. }
  5. //Resolve arr. Make possible to pass both array of settings and list of them.
  6.  
  7. for (var val of arr) {
  8. if (!Array.isArray(val)) {
  9. throw "Wrong type of argument(s).\n All arguments must be arrays.";
  10. }
  11. }
  12.  
  13. return function() {
  14. while(arguments.length > arr.length) {
  15. arr.push([]);
  16. }
  17.  
  18. for (var i = 0;i<arguments.length;i++) {
  19. for (var j = 0;j<arr[i].length;j++) {
  20. if (!arr[i][j](arguments[i]) && arr[i][j].length != 0) {
  21. return false;
  22. }
  23. }
  24. }
  25.  
  26. return func.apply(this, arguments);
  27. }
  28. }
  29.  
  30. //Some predefined stuff.
  31. function isNumber(value) {
  32. return typeof value == 'number';
  33. }
  34. function isString(value) {
  35. return typeof value == 'string';
  36. }
  37. function isSmall(value) {
  38. return value < 100;
  39. }
  40. function isRound(value) {
  41. return !(value % 10);
  42. }
  43.  
  44. //Example.
  45. var sum = function(a,b,c) {
  46. return a+b+c;
  47. }
  48. sum = typeDecorator(sum, [isSmall, isNumber],[isNumber],[isRound]);
  49. //Excessive Arguments and Tests are ok because of While;
  50. //Each set of tests(Even one test) for each argument should be an array.
  51. //The whole thing could be both list of arrays and two-dimensional array.
  52.  
  53. console.log(sum(10,501, 180)); //511
  54. console.log(sum(10,501, 181)); //false
  55. console.log(sum(101,501, 180)); //false
  56. console.log(sum("101",501, 180)); //false
  57. console.log(sum(101,"501", 180)); //false
Add Comment
Please, Sign In to add comment