Call, Apply, Bind and Map

Using different constructs in javascript that allow or make use of the specific properties of functions in javascript.

by Marcus Baptiste

HTML

<div>
  <label>Input: </label> <input type="text" id="textInput"><br>
  <input type="button" value="Filter(map)" id="btnMap">
  <input type="button" value="Apply" id="btnApply">
  <input type="button" value="Bind" id="btnBind">
  <input type="button" value="Call" id="btnCall"><br>
  <label>Output</label>
  <p id="output"></p>
</div>

CSS

input[type=text] {
  margin: 0 5px;
}

JavaScript

var textInput = document.getElementById("textInput");
var btnMap = document.getElementById("btnMap");
var btnApply = document.getElementById("btnApply");
var btnBind = document.getElementById("btnBind");
var btnCall = document.getElementById("btnCall");
var output = document.getElementById("output");


//change str to array of char
var strToArr = function(str) {
	var arr = [];
  var i, len;
  len = str.length;
  for (i=0; i<len; i++) {
  	arr.push(str.charAt(i));
  }
  
  return arr;
};

//call example (display function)
var showOutputA = function(outputText) {
	this.innerHTML = outputText;
}

//apply example (display function advanced)
var showOutputB = function(text1, text2) {
	var outputText = '';
	
  if (text1 === "N") {
  	outputText += "The following characters are not numbers:<br>";
  } else {
  	outputText += text1;
  }
  
	if (text2.constructor === Array)  {
  	outputText += text2.join(',');
  } else {
		outputText += text2;
  }
 
  this.innerHTML = outputText;
};

//map function (filter all characters that are not numberic)
var filterChar = function(char) {
	if (isNaN(char)) {
  	return char;
  }
};

btnMap.onclick = function() {
	var text = textInput.value;
	var chars = strToArr(text);
  var nonNum = chars.map(filterChar);
  showOutputB.apply(output, ["Non numbers: <br>", nonNum]);
};