script.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Рекурсия: HTML tree
  2. // Используя решение этого задания сделайте функцию, которая рекурсивно создает HTML-строку из древовидной
  3. // структуры данных Javascript любой вложенности. Проверьте результат работы функции выводя HTML-строку
  4. // используя document.write или же какой-то_элемент.innerHTML
  5. html_tree: {
  6. function htmlTree(element) {
  7. let str = '';
  8. let attrStr = '';
  9. if (element.attrs) {
  10. Object.keys(element.attrs).forEach(key => {
  11. attrStr += `${key}=${element.attrs[key]} `
  12. });
  13. }
  14. str += `<${element.tagName} ${attrStr}>`
  15. if (element.children) {
  16. for (let childIndex in Object.keys(element.children)) {
  17. if (element.children[childIndex].tagName) {
  18. str += htmlTree(element.children[childIndex]);
  19. } else {
  20. str += `${element.children}`;
  21. }
  22. }
  23. }
  24. str += `</${element.tagName}>`;
  25. return str;
  26. }
  27. const table = {
  28. tagName: 'table',
  29. attrs: {
  30. border: "1",
  31. },
  32. children: [
  33. {
  34. tagName: 'tr',
  35. children: [
  36. {
  37. tagName: "td",
  38. children: ["1x1"],
  39. },
  40. {
  41. tagName: "td",
  42. children: ["1x2"],
  43. },
  44. ]
  45. },
  46. {
  47. tagName: 'tr',
  48. children: [
  49. {
  50. tagName: "td",
  51. children: ["2x1"],
  52. },
  53. {
  54. tagName: "td",
  55. children: ["2x2"],
  56. },
  57. ]
  58. }
  59. ]
  60. }
  61. document.write(htmlTree(table));
  62. }
  63. // Рекурсия: DOM tree
  64. // Используя решение этого задания сделайте функцию, которая рекурсивно создает DOM из древовидной структуры
  65. // данных Javascript. Задание в целом аналогично предыдущему, однако вместо накопления результата в HTML-строке
  66. // функция должна добавлять элементы созданные через document.createElement в переданного в функцию родителя.
  67. dom_tree: {
  68. function domTree(parent, element) {
  69. let el = document.createElement(element.tagName);
  70. if (element.attrs) {
  71. Object.keys(element.attrs).forEach(key => {
  72. el[key] = element.attrs[key];
  73. });
  74. }
  75. parent.append(el);
  76. if (element.children) {
  77. for (let childIndex in Object.keys(element.children)) {
  78. if (element.children[childIndex].tagName) {
  79. domTree(el, element.children[childIndex]);
  80. } else {
  81. el.innerText = element.children;
  82. }
  83. }
  84. }
  85. }
  86. const table = {
  87. tagName: 'table',
  88. attrs: {
  89. border: "1",
  90. },
  91. children: [
  92. {
  93. tagName: 'tr',
  94. children: [
  95. {
  96. tagName: "td",
  97. children: ["1x1"],
  98. },
  99. {
  100. tagName: "td",
  101. children: ["1x2"],
  102. },
  103. ]
  104. },
  105. {
  106. tagName: 'tr',
  107. children: [
  108. {
  109. tagName: "td",
  110. children: ["2x1"],
  111. },
  112. {
  113. tagName: "td",
  114. children: ["2x2"],
  115. },
  116. ]
  117. }
  118. ]
  119. }
  120. domTree(document.body, table);
  121. }
  122. // Рекурсия: Deep Copy
  123. // Напишите функцию, которая рекурсивно осуществляет глубокое копирование структур Javascript, в которых
  124. // нет циклических связей.
  125. deep_copy: {
  126. const table = {
  127. tagName: 'table',
  128. attrs: {
  129. border: "1",
  130. },
  131. children: [
  132. {
  133. tagName: 'tr',
  134. children: [
  135. {
  136. tagName: "td",
  137. children: ["1x1"],
  138. },
  139. {
  140. tagName: "td",
  141. children: ["1x2"],
  142. },
  143. ]
  144. },
  145. {
  146. tagName: 'tr',
  147. children: [
  148. {
  149. tagName: "td",
  150. children: ["2x1"],
  151. },
  152. {
  153. tagName: "td",
  154. children: ["2x2"],
  155. },
  156. ]
  157. }
  158. ]
  159. }
  160. const arr = [1, "string", null, undefined, { a: 15, b: 10, c: [1, 2, 3, 4], d: undefined, e: true }, true, false]
  161. function deepCopy(obj) {
  162. let copy;
  163. if (Array.isArray(obj)) {
  164. copy = [];
  165. } else {
  166. copy = {};
  167. }
  168. if (obj) {
  169. Object.keys(obj).forEach(key => {
  170. if (typeof obj[key] == 'object') {
  171. copy[key] = deepCopy(obj[key]);
  172. } else {
  173. copy[key] = obj[key];
  174. }
  175. });
  176. }
  177. return copy;
  178. }
  179. const arr2 = deepCopy(arr); //arr2 и все его вложенные массивы и объекты - другие объекты, которые можно менять без риска поменять что-то в arr
  180. console.log(arr2);
  181. const table2 = deepCopy(table); //аналогично
  182. console.log(table2);
  183. }
  184. // Рекурсия: My Stringify
  185. // Напишите аналог JSON.stringify
  186. my_stringify: {
  187. function stringify(obj) {
  188. let str = '';
  189. let length = Array.isArray(obj) ? obj.length : Object.keys(obj).length;
  190. if (typeof obj == 'object') {
  191. str += Array.isArray(obj) ? '[' : '{';
  192. }
  193. Object.keys(obj).forEach((key, i) => {
  194. if (!Array.isArray(obj)) {
  195. str += `"${key}":`;
  196. }
  197. if (typeof obj[key] == 'object' && obj[key] != null) {
  198. str += stringify(obj[key]);
  199. } else if (typeof obj[key] == 'string') {
  200. str += `"${obj[key]}"`;
  201. } else if (obj[key] == undefined) {
  202. str += `null`;
  203. } else {
  204. str += `${obj[key]}`;
  205. }
  206. if (i != length - 1) {
  207. str += ',';
  208. }
  209. });
  210. if (typeof obj == 'object') {
  211. str += Array.isArray(obj) ? ']' : '}';
  212. }
  213. return str;
  214. }
  215. const arr = [1, "string", null, undefined, { a: 15, b: 10, c: [1, 2, 3, 4], d: undefined, e: true }, true, false];
  216. const jsonString = stringify(arr); //напишите функцию stringify без использования JSON.stringify
  217. console.log(jsonString);
  218. console.log(JSON.parse(jsonString));//не должно поломаться и должно вернуть структуру, во всем схожую с оригинальным arr или table
  219. }
  220. // Рекурсия: getElementById throw
  221. // Напишите функцию getElementById, которая будет аналогична document.getElementById. В качестве основы можете
  222. // взять материал лекции (walker), однако в цикл перебора children вставьте проверку на нахождение
  223. // переданного id. При нахождении элемента по id в рекурсивной функции выбрасывайте исключение со значением
  224. // найденного DOM-элемента, которое будет поймано на уровне вашей функции getElementById, после чего она
  225. // вернет выброшенный DOM-элемент.
  226. get_element_by_id: {
  227. function getElementById(idToFind) {
  228. function walker(parent = document.body) {
  229. for (const child of parent.children) {
  230. if (child.id == idToFind) {
  231. throw child;
  232. }
  233. walker(child);
  234. }
  235. }
  236. try {
  237. walker();
  238. } catch (e) {
  239. return e;
  240. }
  241. }
  242. console.log(getElementById('wantedParagraph'));
  243. }