main.js 1.8 KB

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