0

I'm trying to do a basic crud operation in angular using linked list with NgRx (state management)

  • I created a node with value "1" and 1st time head and tail is updated
  • 2nd time, I created another node with value "2"
  • tail node is "1". and it's next field is null, now I update the next field with new node (i.e : "2"), and I update the new node (i.e : 2) as tail node.
  • Now when I console the head, it will print me as

without NgRx concept:

Node { data: 1, next: { data :2, next: undefined } }

with NgRx concept:

Node { data: 1, next: undefined }

I think, since, NgRx state is immutable, so when I change the tail node, it is not reflecting in head node.

In alternate way, I can also append a second node straightly in head, by checking each node next field is null or not to find the last node, but this will iterate many times if we have lots of node.

Is there any other way? I'll post my code below.

emp.state.ts:

export const initialState = {
    empData:{
        head: null,
        tail: null,
        length: 0,
    },
} 

emp.action.ts:

import { createAction, props } from "@ngrx/store"

export const addEmp = createAction(
    'addEmp',
    props<{empObj:any}>()
)

emp.reducer.ts:

import { createReducer, on } from "@ngrx/store"
import { initialState } from "./emp.state"
import { addEmp } from "./emp.action"

export class Node {
    private data: Node;
    private next: Node | null;
    
    constructor(data:any, next?:any) {
        this.data = data
        this.next = next
    }
}

export const empReducer = createReducer(
    initialState,
    on(addEmp, (state: any, { empObj }) => {
        const newNode = new Node(empObj);

        // If the linked list is empty
        if (!state.empData.head) {
            return {
                ...state,
                empData: {
                    head: newNode,
                    tail: newNode,
                    length: state.empData.length + 1
                }
            };
        }
        
        // Make the last item refer to the newly added node
        const newTail = new Node(empObj);
        const updatedTail = { ...state.empData.tail, next: newTail };

        return {
            ...state,
            empData: { // Make the newly added node the last/tail node
                ...state.empData,
                tail: updatedTail,
                length: state.length + 1
            }
        }
    }),
)
  • 2
    It is not efficient to use a linked list if you are going to add elements at the end **and** need to copy the list. It is much more interesting to **prepend** nodes to the existing list, since then the nodes you already had can remain as-is. – trincot Jun 11 '23 at 14:06
  • Thankyou for this idea, I try this – Kathiravan S Jun 20 '23 at 09:15

0 Answers0