A7: JS Code interpretation

Assignment Series #A7 – Journeyman’s Piece

Part 1

This time around, we’ll write and analyze some short pieces of code.  Write three implementations calculating the factorial (n!, see Wikipedia 2 for more information) and submit them in file(s) with a .js extension.

  1. Use a manual loop
  2. Use reduce
  3. Don’t use keywords except function and return. and don’t use any operators except *

Calculate factorial with for loop

const factorialOf = integer => {
  let factorial = 1;

  for(let i = 1; i <= integer; i++) {
    factorial *= i;
  }

  return factorial;
}

console.log(factorialOf(5));  // 120

Calculate factorial with for loop

var array = [ ];

function factor(num) {
    for (i = 1; i <= num; i++) {
      array.push(i);
    }  
    return array.reduce(function(a, b) {
      return a * b;
    },1)
  };
  
  console.log(factor(5)); // 120

Calculate factorial with recursion

  function factorialize(num) {
  if (num < 0) 
        return -1;
  else if (num == 0) 
      return 1;
  else {
      return (num * factorialize(num - 1));
    }
}
factorialize(5); // 120

Part 2

Analyze the code below and write down answers to the following:
  • What would be good names for whatAmI, foo, and bar?
  • Explain line by line what the code does – you may have to do some research

 

// Create a fuction called whatAmI with two input fields foo and bar  
const whatAmI = (foo , bar ) => {

  // If bar is null then return foo
  if (!bar) {return foo; }

  // method JSON.stringify will be applied to foo and then passed to method JSON.parse. Content of result is equivalent to content of foo 
  const result = JSON.parse (JSON.stringify (foo));

  // Execute function keys on bar. On the obtained list execute the forEach method. forEach method gets anonymous function
  Object.keys (bar).forEach ((key) => {

    // look in map bar which value is stored in key. Then assign this content to the variable value.
    const value = bar [key];

    // check if variable value = null 
    if ( value === null ) {

      // check if value of result for key is null and if not then remove value in result for key.
      result [key] && delete result [key];

      // check if value is not undefined
    }  else if ( value !== undefined ) {

      // check if value is an array
        if ( Array.isArray (value)) {

          // if yes, generate error message "Array elements not supported!" 
          // program will be terminated
          throw " Array elements not supported !";

          // check if value is an object and if value for key is not null
        } else if ( typeof value === " object " && foo [key]) {
          
          // call method whatAmI again. As first input for the method whatAmI the value in foo is passed to key. the variable value is the second input. 
            result [key] = whatAmI (foo [key], value );
        } else {
          // value of variable value will be written in key
            result [key] = value ;
        }
    }
    });
    // return value of method whatAmI
  return result;
 }

Conclusion

I’d call this program the limited overwriter:
  • foo will be overwritten by bar, but not in every case…
  • bar does not replace foo in the keys that are not included in both maps.
  • bar adds the keys and the corresponding values to foo that were contained in bar but not in foo before.
  • print error message if array contained.

Ressources

 [1] https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
 [2] https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
 [3] https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions
 [4] https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Map

 

PDF Report
JP_JS#1