LinkedList Generator

JS
S
JavaScript

Based on this: const nodes = [ { id: '0', to: '1' }, { id: '1', to: '2', pre: true }, { id: '2', to: '3', post: true }, { id: '3', to: '4', pre: true, post: true }, { id: '4' }, ]; Will generate this: const expected = { '0.5': '1.1', '1.1': '1.5', '1.5': '2.5', '2.5': '2.9', '2.9': '3.1', '3.1': '3.5', '3.5': '3.9', '3.9': '4.5', '4.5': null, };

1function generateLinkedList(nodes) {
2  const intermediateArray = [];
3
4  for (let i = 0; i < nodes.length; i++) {
5    const currentId = (parseFloat(nodes[i].id) + 0.5).toString();
6
7    // If there is a 'pre' condition on this node and it's not the first node,
8    // add an additional node before it
9    if (nodes[i].pre && i !== 0) {
10      intermediateArray.push({
11        id: (parseFloat(nodes[i].id) + 0.1).toString(),
12      });
13    }
14
15    // Add the current node
16    intermediateArray.push({
17      id: currentId,
18    });
19
20    // If there is a 'post' condition on this node and it's not the last node,
21    // add an additional node after it
22    if (nodes[i].post && i !== nodes.length - 1) {
23      intermediateArray.push({
24        id: (parseFloat(nodes[i].id) + 0.9).toString(),
25      });
26    }
27  }
28
29  // Now, construct the final linked list from the intermediate array
30  const linkedList = {};
31  for (let i = 0; i < intermediateArray.length - 1; i++) {
32    linkedList[intermediateArray[i].id] = intermediateArray[i + 1].id;
33  }
34  linkedList[intermediateArray[intermediateArray.length - 1].id] = null; // The last node points to null
35
36  return linkedList;
37}
38
39const nodes = [
40  { id: '0', to: '1' },
41  { id: '1', to: '2', pre: true },
42  { id: '2', to: '3', post: true },
43  { id: '3', to: '4', pre: true, post: true },
44  { id: '4' },
45];
46
47console.table(generateLinkedList(nodes));
48

Created on 7/5/2023