javascript

Ch4. A list

READ MORE

Source


function arrayToList(array) {
  var list = null;
  for (var i = array.length - 1; i >= 0; i--)
  {
    list = {value: array[i], rest: list};
  }
  return list;
}

function listToArray(list) {
  var array = [];
  for (var node = list; node; node = node.rest)
  {
    array.push(node.value);
  }
  return array;
}

function prepend(value, list) {
  return {value: value, rest: list};
}

function nth(list, n) {
  if (!list)
  {
    return undefined;
  }
  else if (n == 0)
  {
    return list.value;
  }
  else
  {
    return nth(list.rest, n - 1);
  }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]
console.log(prepend(10, prepend(20, null)));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20

Ch4. Reversing an array

READ MORE

Source


//Reverse an array by pushing
function reverseArray(arr)
{
  var revArr = [];
  for(var i=arr.length-1;i>=0;i--) 
  {
     revArr.push(arr[i]);
  }
  return revArr;
}

//Reverse an array by swapping
function reverseArrayInPlace(arr) 
{
  for(var i=0;i<=Math.floor(arr.length/2);i++)
  {
      var t = (arr.length-1)-i;
      var temp = arr[t];
      arr[t] = arr[i];
      arr[i] = temp;
  }
  return arr;
}

console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]

Ch4. The sum of a range

READ MORE

Source


// Builds an array containing all numbers from start up to (and including) end, with optional step parameter.
function range(start, end, step)
{
  var arr = [];
  
  // Set default step if step not present
  if(arguments.length == 2 && start<end)
  {
    step = 1;
  }
  else if(arguments.length == 2)
  {
    step = -1;
  }

  // Counting up(step is positive)
  if(step>0)
  {
    while(start<=end)
    {
      arr.push(start);
      start+=step;
    }
  }
  // Counting down(step is negative)
  else
  {
    while(start>=end)
    {
      arr.push(start);
      start+=step;
    }
  }
  return arr;
}

// Takes an array of numbers and returns sum
function sum(numArr)
{
  var count=0;
  for(var i=0;i<numArr.length;i++)
  {
    count += numArr[i];
  }
  return count;
}

console.log(sum(range(1, 10)));
// → 55
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]

testing .replace()

READ MORE


var firstPost = "this is my first post";
var secondPost = "this ismysecond post";

var test = [];
test.push(firstPost);
test.push(secondPost);

test.forEach(function(m){
  console.log(m.indexOf(" ") ? m.replace(/\s/gi,"KAPPA") : null);
});