Skip to content

Instantly share code, notes, and snippets.

@vovanmix
Last active February 27, 2017 05:30
Show Gist options
  • Save vovanmix/4cc621370fdf2ea13ab8824ec653ef07 to your computer and use it in GitHub Desktop.
Save vovanmix/4cc621370fdf2ea13ab8824ec653ef07 to your computer and use it in GitHub Desktop.
javascript snippets
/**
* Functor takes a value and a function, splits the value, feeds the value to the function and returns the result
* Examples: .map(), .filter()
*/
function F(value, fn){
return fn(value);
}
F(1, plus1); //2
function stringFunctor(value, fn) {
var chars = value.split("")
return chars.map(function(char) {
return String.fromCharCode(fn(char.charCodeAt(0)))
}).join("")
}
stringFunctor("ABCD", plus1) // ==>> "BCDE"

Currying

import _ from 'lodash';

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curry(abc);

curried(1)(2)(3);
// → [1, 2, 3]

Factory function

function Car (make, model, color) {
  var self = {
    make: make,
    model: model,
    color: color,
    paint: function(color){
      self.color = color;
    }
  };
  return self;
}
 
var myCar = Car();

Foreach / Filter / Map / Reduce http://colintoh.com/blog/5-array-methods-that-you-should-use-today

arr.forEach(function(item,index){
	console.log(item);
});

var newArr = arr.filter(function(item){
    return item.name === "orange";
});

var newArr = arr.map(function(item,index){
    item.full_name = [item.first_name,item.last_name].join(" ");
    return item;
});
var newArr = arr.map(function(item,index){
    return [item.first_name,item.last_name].join(" ");
});

return arr.reduce(function(prev,next){
    prev[next] = (prev[next] + 1) || 1;
    return prev;
},{});
return arr.reduce(function(sum,item){
    return sum + item.value;
},0);

Demethodizing

// Demethodizing the Array method, forEach(),  into a generic "each"
var each = Function.prototype.call.bind([].forEach);
var nodeList = document.querySelectorAll("p");
each(nodeList,bold);
function bold(node){
   node.style.fontWeight ="bold";
}

var str = '12345';
Array.prototype.map.call(str, function(x) {
  return x;
}).reverse().join(''); 

In operator

var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar  // returns true
"model" in mycar // returns true

Arrays methods

return [1,2,3].indexOf(2);

var myArray = ['one', 'two', 'three'];
myArray.reverse(); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment