main.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // ES6
  2. // a
  3. let a = () => alert('Привет')
  4. a()
  5. // cube
  6. let cube = () => console.log(prompt('number') ** 3);
  7. cube()
  8. // avg2
  9. let avg2 = (a, b) => {
  10. a = +prompt('num1')
  11. b = +prompt('num2')
  12. console.log((a + b) / 2);
  13. }
  14. avg2()
  15. // sort
  16. var persons = [
  17. { name: "Иван", age: 17 },
  18. { name: "Мария", age: 35 },
  19. { name: "Алексей", age: 73 },
  20. { name: "Яков", age: 12 },
  21. ]
  22. function sort(persons, key, ok = true) {
  23. return persons.sort((a, b) => {
  24. let result;
  25. if (ok) { result = a[key] > b[key] ? 1 : -1; }
  26. else { result = a[key] < b[key] ? 1 : -1; }
  27. return result;
  28. })
  29. }
  30. console.log(sort(persons, "age"));
  31. ///////////////////////////////////////////////
  32. console.log(sort(persons, "name", false));
  33. ///////////////////////////////////////////////
  34. console.log(sort(persons, "name"));
  35. // array map
  36. var numbers = ["1", {}, null, undefined, "500", 700].map(function (a) { if ((+a) > 0) return +a; else return a })
  37. console.log(numbers)
  38. // array reduce
  39. let number01 = ["0", 5, 3, "string", null];
  40. let number02 = number01.filter(item => typeof item === 'number').reduce((a, b) => a * b)
  41. console.log(number02)
  42. // object filter
  43. var phone = {
  44. brand: "meizu",
  45. model: "m2",
  46. ram: 2,
  47. color: "black",
  48. };
  49. function filter(object, callback) {
  50. let filterPhone = {}
  51. for (let key in object) {
  52. if (callback(key, object[key]))
  53. filterPhone = { ...filterPhone, [key]: object[key] };
  54. }
  55. return filterPhone;
  56. }
  57. console.log(filter(phone, (key, value) => key == "color" || value == 2));
  58. // object map
  59. function objectMap(object, callback) {
  60. let filter = {}
  61. for (let key in object) {
  62. filter = { ...filter, ...callback([key], object[key]) };
  63. }
  64. return filter;
  65. }
  66. let finish = objectMap({ name: "Иван", age: 17 }, function (key, value) {
  67. var result = {};
  68. result[key + "_"] = value + "$";
  69. return result;
  70. })
  71. console.log(finish)
  72. // Рекурсия
  73. // Sum
  74. let fact = n => n <= 0 ? 0 : n + fact(n - 1);
  75. console.log(fact(0))
  76. console.log(fact(1))
  77. console.log(fact(3))
  78. console.log(fact(5))
  79. console.log(fact(7))
  80. console.log(fact(9))