Skip to content

Instantly share code, notes, and snippets.

@Elijah-trillionz
Created October 26, 2021 18:31
Show Gist options
  • Save Elijah-trillionz/beeed534e900d4b0af6a3d2bd06f12fb to your computer and use it in GitHub Desktop.
Save Elijah-trillionz/beeed534e900d4b0af6a3d2bd06f12fb to your computer and use it in GitHub Desktop.
JavaScript lists
// convert from array to list with
function arrayToList(arr) {
// list format: value 1, rest => value 2, rest => value 3, rest => null
let list;
for (let i = arr.length; i >= 0; i--) {
list = {
value: arr[i],
rest: i >= arr.length - 1 ? null : list,
};
}
return list;
}
// convert from list to array with
function listToArray(list) {
const arr = [];
for (let node = list; node; node = node.rest) {
arr.push(node.value);
}
return arr;
}
// prepend to list with
function prepend(element, list) {
let count = 0;
for (let node = list; node; node = node.rest) {
if (count === 0) {
list = {
value: element,
rest: list,
};
}
count++;
}
return list;
}
// find nth (zero-based) value in list with
function nth(list, number) {
let count = 0;
let result;
for (let node = list; node; node = node.rest) {
if (count === number) {
res = node;
}
count++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment