"Trick" JS Questions

Currying, closure, hoisting, oh my!

by robotsgoboop

HTML

<div id="out">

</div>

JavaScript

// "Trick" JS Questions

function print(msg) {
	document.querySelector('#out').innerHTML += `<p>${msg}</p>`;
}

/*
*	Write a function that can be called as add(2, 3) and add(2)(3). Will only support for 2 numbers
*/

function curriedAdd(...args) { // assumes all args are numbers
  if (args.length === 0) {
    return 0; // or some error
  }
  else if (args.length === 1) { // curry
    const a = args[0];
    return function(b) {
      return a + b;
    }
  } 
  else {
    return args[0] + args[1];
  }
}

print(curriedAdd(2, 3));
print(curriedAdd(2)(3));
addTwo = curriedAdd(2);
print(addTwo(5))

/*
* The loop should print out 0, 1, 2, 3, 4, but it doesn't. Why? Fix it.
*/

// prints 5, 5, 5, 5, 5
function brokenClosure() {
	for (var i = 0; i < 5; i++) {
  	setTimeout(function() {
    	print(i);
    }, i * 100);
  }
}

// prints 0, 1, 2, 3, 4
function fixedClosureES5() {
	for (var i = 0; i < 5; i++) {
  	setTimeout((function(x) {
    	return function() {
    		print(x);
      }
    })(i), i * 100);
  }
}

// prints 0, 1, 2, 3, 4
function fixedClosureES6() {
	for (let i = 0; i < 5; i++) {
  	setTimeout(function() {
    	print(i);
    }, i * 100);
  }
}

// Commented out because timeouts make the printint look weird.
/* brokenClosure(); */
/* fixedClosureES5(); */
/* fixedClosureES6(); */

/*
*	What is the output of this code? 
*/

// prints undefined, goodbye, hello, goodbye
function brokenHoisting() {
	var hello = 'hello';
  var goodbye = 'goodbye';
  function act() {
  	print(hello);
    print(goodbye);
    var hello = 'hola'; // declaration is hoisted to top of act()
  }
  act();
  print(hello);
  print(goodbye);
}

brokenHoisting();


// Write a function that *eventually* returns a value, but the computation itself is asynchronous because it takes a significant amount of time
// It should not block the main thread, and returns a promise.
// How do you work with a function like this?
// How do you know when the computation is finished, and how do you get the...