JSFiddle - React, Tailwind, and code Playground

by Darby Rathbone

JavaScript

/*
Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
 
 
*/
 
function arrayToList(array){
 
   var savedArray = array.slice();
     
    var element = {value:savedArray.shift()};
     var ele = element;
   while(savedArray.length){
       ele.rest = {value:savedArray.shift()}
      ele = ele.rest;
   }
   
   return element;
}
var prepend = function(element,list){
    return {value:element,rest:list};   
};
var list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};
 
function listToArray(list){
 
  var array = [];
     console.log(list);
  for (var node = list; node; node = node.rest) {
 
      array.push(node.value);
  }
     
   return array;
}
 console.log(listToArray(prepend(0,list)));
var list2 = arrayToList([1,2,3]);
//list2 = list;
console.log(listToArray(list2));
//console.log(list2);
//console.log(list == list2);