16 January 2016

Recursion performance test

As I've read multiple times, recursion while being more elegant is most of the times slower than a regular loop. I tested this with jsperf on a simple factorial function. Here is the JSperf link if you want to test on your own machine.

Recursion:
 
function factorialize(num) {
  if (num <= 0) {
    return 1;
  }
  return num * (factorialize(num-1));
}

factorialize(5);

Result: 30,406,485 Ops/sec
±0.51%
59% slower



Basic for loop:

function factorialize(num) {
 var result = 1;
  for (i = 1; i <= num; i++) {
 result = result * i;
  }
return result;
}

factorialize(5);

Result:
73,615,404 Ops/sec
±0.47%
fastest

15 January 2016

Eloquent Javascript: Minimum

The previous chapter introduced the standard function Math.min that returns its smallest argument. We can do that ourselves now. Write a function min that takes two arguments and returns their minimum.

function min(a, b) {
  if (a < b) {
    return a;
  }
  return b;
}

console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10

14 January 2016

Eloquent Javascript - Looping a triangle


function oneMore(num, str) {
  var line = "";
  for (i = 0; i < num; i++) {
    console.log(line += str);
  } 
}
oneMore(7, "#");

Eloquent Javascript - FizzBuzz


function fizzbuzz(num, fizz, buzz) {    
 for (i = 1; i <= num; i++) {    
     if (i % (fizz * buzz) === 0) {
         console.log("FizzBuzz");
     } else if (i % buzz === 0) {
         console.log("Buzz");
     } else if (i % fizz === 0) {
         console.log("Fizz");
     }   
 }  
}    

fizzbuzz(100, 3, 5);

Eloquent Javascript - Chess Board

My solution:

function checkerMaker(size, symbols) {
  
  for (i = 0; i < size; i++) {
    var line = "";
    if (i % 2 === 0) {
      for (j = 0; j < (size/2); j++) {
        line += symbols;
      }
        console.log(line);  
    } else {
      var altSymbols = symbols.split("").reverse().join("");
      for (j = 0; j < (size/2); j++) {
        line += altSymbols;
      }
        console.log(line); 
    }
  }

}

checkerMaker(8, " #");

I knew I was repeating myself when I wrote the second inner for loop. Still havn't got the maths instinct.

Marijn Haverbeke's solution:

function checkerMaker(size, symbol1, symbol2) {
var board = "";
for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += symbol1;
    else
      board += symbol2;
  }
  board += "\n";
}
console.log(board);
}
checkerMaker(8, " ", "#");

17 November 2015

Bonfire: Chunky Monkey


function chunk(arr, size) {

  var multi = [];
  i = 0;
  
  while (i < arr.length){
    multi.push(arr.slice(i,i+=size));
  }
  return multi;
}

chunk(["a", "b", "c", "d"], 1);


Here an alternative where I extracted the increment i=i+size, for more readability (maybe?):

function chunk(arr, size) {

  var multi = [];
  i = 0;
  
  while (i < arr.length){
    multi.push(arr.slice(i,i+size));
    i=i+size;
  }
  return multi;
}

chunk(["a", "b", "c", "d"], 1);


Same with a for loop instead of while:

function chunk(arr, size) {

  var multi = [];
  for (i=0;i < arr.length;i+=size){
    multi.push(arr.slice(i,i+size));
  }
  return multi;
}

chunk(["a", "b", "c", "d"], 2);

Bonfire: Truncate a string

My low bro solution, it's ugly, and still took me time...

function truncate(str, num) {
  
  if(num <= 3){
    return str.slice(0,num) + "...";
  }
   if(str.length > num){
    return str.slice(0,num-3) + "...";
  }
   if(num >= str.length){
    return str;
  }
}

truncate("A-tisket a-tasket A green and yellow basket", 2);

It took me time because I literally translated this instructions "If the length of the string is less than or equal to 3 characters" as this:

  if(str.length <= 3){
    return str.slice(0,num) + "...";
  }
instead of course, of this:

  if(num <= 3){
    return str.slice(0,num) + "...";
  }
akshat01 posted this on Gitter in the HelpBonfires room and it's way more concise:

function truncate(str, num) {

  var i= 0;
  if (num >=3){
    i=3;
  }

  if (str.length> num){
    str= str.slice(0,num-i)+"...";}
  return str;
} 

truncate("A-tisket a-tasket A green and yellow basket", 1);

I don't know what it says about me but it took me a good 15 mins to understand the logic of just returning the str as is, in fact the default value since both "if" statements covered all other cases

13 November 2015

Bonfire: Repeat a string repeat a string

My solution:

function repeat(str, num) {
  var singles = [];
  if (num <= 0){
   repeatedStr="";
  }
  for(i=0;i<num;i++){
    singles.push(str);
    repeatedStr = singles.join("");
  }
  return repeatedStr;
}

repeat("abc", 3);

Critics:
- I still make stupid mistakes regarding variables scope and had at first put var singles = []; inside the for loop...
- I repeat myself when instead of directly returning singles.join("") I assign it first to repeatedStr. Only advantage I could see is if we further down the road would want to access this variable.

---

Now, FFC on their wiki, have this similar one:

function repeat(str, num) {
  var newstr = [];
  for (var i = 0; i < num; i++) {
    newstr.push(str);
  };
  return newstr.join('');
}

repeat("abc", 3, "");


Ok, it's still a simple one but more elegant, it gets rid of the if condition by inserting the empty string as an argument. Since we havn't seen this in the previous Javascript Waypoints, I assume it means a sort of "false default" value. I've tried to google it but since I don't know how this notation style is named, it's very hard to find something relevant. If anyone got any idea feel free to tell in the comments.

12 November 2015

Bonfire: Return Largest Numbers in Arrays

So, for this bonfire, you get the comparison operators as a link/hint. Nice troll.

function largestOfFour(arr) {
//create empty array to store the biggest numbers the function will return
  var biggest = [];  

//loop through each main array indexes
  for(var i = 0; i < arr.length; i++){
    //create variable to sub-arrays biggest number the function (yet not written) will return
    var temp = 0;
    biggest[i] = temp;
  }
  return biggest;
}
largestOfFour([[1000, 1001, 857, 1], [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


Now add this.

function largestOfFour(arr) {
  var biggest = [];
  for(var i = 0; i < arr.length; i++){
    var temp = 0;
    for(var j = 0; j &lt arr[i].length; j++){
      if(arr[i][j] &gt temp){
        temp = arr[i][j];
      }
    }
    biggest[i] = temp;
  }
  return biggest;
}
largestOfFour([[1000, 1001, 857, 1], [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
See the Pen ClnAe by Katja Hollar (@afkatja) on CodePen