Message from JavaScript discussions

August 2017

— Yes?

— 

This is the function i use to do it using mutable nature of list

function postpendList(list, element){
var newElement = { value: element,
rest: null
};
var current = list;

while(current.rest != null){
current = current.rest;
}

current.rest = newElement;
}

— I uderstand this one

— This i don't understand

— ??

— I'll make a function :P

— And thanks TRGWII for the help !!

— That will be great 😁

— 

function add(list, value) {
let inner = list;
const values = [];
while (inner.rest) {
values.unshift(inner.value);
inner = inner.rest;
}
let result = { ...inner };
result.rest = { value, rest: null };
for (const value of values)
result = { value, rest: result };
return result;
}

Message permanent page

— Here's an iterative approach

— 

> list
{ value: 0, rest: { value: 1, rest: null } }
> add(list, 2)
{ value: 0, rest: { value: 1, rest: { value: 2, rest: null } } }
> list
{ value: 0, rest: { value: 1, rest: null } }

Message permanent page

— This shows that the add function returns a new list, while the original remains unchanged