Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. <script>
  2. // 1. Write a function which will return these outputs.
  3.  
  4. // f(1)(2)(3); // 9
  5. // f(2)(2)(1); // 4
  6. // f(2, 2, 1); // 4
  7. // f(); // 0
  8.  
  9. function result(a, b, c) {
  10. if (a && b && c) {
  11. return (a + b) * c;
  12. } else if (a && b) {
  13. return function(val) {
  14. return (a + b) * val;
  15. }
  16. } else if (a) {
  17. return function(val1) {
  18. return function(val2) {
  19. return (a + val1) * val2;
  20. }
  21. }
  22. } else {
  23. return 0;
  24. }
  25. }
  26.  
  27. console.log(result(1)(2)(3)); // 9
  28. console.log(result(2)(2)(1)); // 4
  29. console.log(result(2, 2, 1)); // 4
  30. console.log(result(2, 2)(2)); // 8
  31. console.log(result()); // 0
  32.  
  33. // 2. let say an object is there. Convert into array which stores only the values of the object.
  34. // x = {
  35. // a: 1, // name: value pairs
  36. // b: 2
  37. //};
  38.  
  39. const nameArr = [];
  40. const valArr = [];
  41.  
  42. for(let i in x) {
  43. nameArr.push(i); // prints name
  44. valArr.push(x[i]); // prints value
  45. }
  46.  
  47. console.log(nameArr); // ["a", "b"]
  48. console.log(valArr); // [1, 2]
  49.  
  50. // 3 . Reverse a string.
  51.  
  52. const reverseString = (str) => str.split('').reverse().join('');
  53. console.log(`Reverse of the string: ${reverseString('amrit')}`); // Reverse string: tirma
  54.  
  55. // 4. Modify the code so that newObj.getA().getB(); should not return undefined
  56.  
  57. const newObj = {
  58. a: 1,
  59. b: 2,
  60. getA() {
  61. console.log(this.a);
  62. return this; // add this line
  63. },
  64. getB() {
  65. console.log(this.b);
  66. }
  67. }
  68.  
  69. newObj.getA().getB();
  70.  
  71. // 5. Add all the elements of an array.
  72. let addArr = [1, 2, 5, 6, 8];
  73.  
  74. let resultArr = addArr.reduce((acc, item) => acc + item, 0);
  75.  
  76. console.log('Result array after reduce: ' + resultArr); // Result array after reduce: 22
  77.  
  78. // 6. Show the output of the following.
  79. console.log([] + []); // empty string
  80. console.log([] + {}); // [object Object]
  81. console.log({} + {}); // [object Object][object Object]
  82.  
  83. // 7. Write a program to find factorial.
  84.  
  85. function factorial(number) {
  86. if (number <= 1) {
  87. return 1;
  88. }
  89. return number * factorial(number - 1);
  90. }
  91.  
  92. document.write(factorial(6))
  93.  
  94. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement