Message from JavaScript discussions
August 2017
— 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;
}
— 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 } }
— This shows that the add function returns a new list, while the original remains unchanged
— Thanks TRGWII for all the help 😁
— Why are you doing linked lists in JS though?
— Why not just arrays?
— I'm doing practice with all exercise problems of eloquent js
— Beware, this has to copy every part of the list by neccessity
— So it might be memory-intensive
— So when i was doing that i got a doubt related to that