Functional Programming

Change class name on click in jQuery

by black strings

HTML

<div id="con">

</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  color: white;
}

JavaScript

// find elements
// dom ready
$(() => {
	var con = $("#con");
	var tArr1 = [2,3,1,5];
  var tArr1a = [1,2,3];
  var tArr2 = [[1,2,3],[4,5,6]];
  var tArr3 = [
  	{
    	category: "new",
      dogs: [
      	{id: 101, name: "Tom", age: 5},
        {id: 34, name: "Sam", age: 11},
        {id: 252, name: "Mary", age: 7}
      ]
    },
    {
    	category: "old",
      dogs: [
      	{id: 432, name: "Lo", age: 1},
        {id: 333, name: "Bill", age: 3},
        {id: 111, name: "Kim", age: 5}
      ]
    }
  ];
  
  // example of concat all
  var sampleConcatAll = function(){
  	var r = tArr3.map((item) => {
      return item.dogs.map((dog) => {
        return {id: dog.id, name: dog.name}
      });
    }).concatAll();	// if using prototype, will not work with typescript
    console.log(r);
  }
  // example of concatMap without having to write concatAll
  var sampleConcatMap = function(){
  	var r = tArr3.concatMap((item) => {
      return item.dogs.map((dog) => {
        return {id: dog.id, name: dog.name}
      });
    });
    console.log(r);
  }
  // example of zip
  var sampleZip = function(){
  	var result = Array.zip(tArr1, tArr1a, (l,r) => {return l + r});
    console.log(result);
  }
  
  var sampleSeq = function(){
  	
  }
  
  // ------------ playground
  //sampleConcatAll();
  //sampleConcatMap();
  sampleZip();
  //sampleSeq();
  
});

// custom reduce that returns an array instead of a value unlike native reduce()
Array.prototype.reduceCustom = function(combiner, initialValue) {
	var counter,
		accumulatedValue;

	// If the array is empty, do nothing
	if (this.length === 0) {
		return this;
	}
	else {
		// If the user didn't pass an initial value, use the first item.
		if (arguments.length === 1) {
			counter = 1;
			accumulatedValue = this[0];
		}
		else if (arguments.length >= 2) {
			counter = 0;
			accumulatedValue = initialValue;
		}
		else {
			throw "Invalid arguments.";
		}

		// Loop through the array, feeding the current value and the result...