Category Archives: javascript

How to add utm_params to links

How to add utm query params to every external link on your blog

Every digital marketing knows the importance of utm query parameters, basically those text like utm_source=”” in your browser window location bar.
Its a great way to slice and dice and find out where traffic is coming from, which campaigns are more effective, is social working as expected.
Lets say you want to add these query params to your blog post so that the websites owners to whom you are linking can easily know how many clicks are coming through the website.
I had such a requirement for my blog http://jquer.in/ which now contains more than 5000 (function addUtmParams(source, medium, campaign) { $("a").each(function () { var $this = $(this); var linkHref = $this.attr("href"); if (linkHref.indexOf(window.location.hostname) < 0) { var updateLink = updateQueryString({ utm_source: source, utm_medium: medium, utm_campaign: campaign }, linkHref); $this.attr("href", updateLink); } }); })("jquer.in", "website", "content-curation"); // The thee configurable options ( utm_source, utm_medium, utm_campaign) // In my case source is jquer.in, medium is website, campaign is content-curation // Inspired from http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter function updateQueryString(params, url) { if (!url) url = window.location.href; for (var key in params) { if (params.hasOwnProperty(key)) { var value = params[key]; var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"); if (re.test(url)) { if (typeof value !== ‘undefined’ && value !== null) return url.replace(re, ‘$1′ + key + "=" + value + ‘$2$3′); else { var hash = url.split(‘#’); url = hash[0].replace(re, ‘$1$3′).replace(/(&|\?)$/, ”); if (typeof hash[1] !== ‘undefined’ && hash[1] !== null) url += ‘#’ + hash[1]; } } else if (typeof value !== ‘undefined’ && value !== null) { var separator = url.indexOf(‘?’) !== -1 ? ‘&’ : ‘?’, hash = url.split(‘#’); url = hash[0] + separator + key + ‘=’ + value; if (typeof hash[1] !== ‘undefined’ && hash[1] !== null) url += ‘#’ + hash[1]; } } } return url; }

View the functions file of jquer.in

Heres a gist

You can add the code to your functions.js or a javascript file of your wordpress theme.
Let me know what you think in the comments :-

javascript reduce

javascript reduce method

The javascript reduce method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

Directly copied from MDN

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Summary :-

The reduce method is an acculumator function that provides a simpler way to loop through any javascrpt array from left to right and perform incremental function on all the values.

Some examples to help better understand .reduce

1.Calculate the Sum

var calculateSum = function (a) {
	return a.reduce(function  (i,c) {
		return i+c
	});
}

console.log(calculateSum([1,2,3,4])); // <= 10

2.Calculate the product of all the elements of the array :-

var calculateProduct = function  (a) {
	return a.reduce(function  (i,c) {
		return i*c;
	});
}

console.log(calculateProduct([1,2,3,4])); <= 24

3. Calculate the sum of even elements


/* This can be achieved better by using filter Ex.5 */

[1,2,3,4].reduce(function(a,b,i){
  if(i%2 === 0){ 
   return a+b;
  }else{
   return a;
  }
}); //<= 4


4. Flatten an array

var flattenArray = function  (a) {
	return a.reduce(function  (i,c) {
		return i.concat(c);
	})
}

var b = [[1,2,3],[2,3,4],[4,5,6]];

console.log(flattenArray(b)); //<= [ 1, 2, 3, 2, 3, 4, 4, 5, 6 ]

4. Flatten any array of any level recursively

Here we are passing the second argument as an empty array as that will be the initial value of the accumulator.


var b = [2,[1,2,[3,4]],[2,3,4],[4,5,6]];

var flattenRecursive = function  (arr) {
	return arr.reduce(function  (a,b) {
		if (b instanceof Array) {
			return a.concat(flattenRecursive(b));
		}else{
			return a.concat(b);
		}
	},[]);
}

console.log(flattenRecursive(b)); //<= [ 2, 1, 2, 3, 4, 2, 3, 4, 4, 5, 6 ]

5. Using with filter to solve Ex.2

Using filter with reduce makes looping through any array and performing any function much easy.


var filterEvenSum = function  (arr) {
	return arr.filter(function  (a,i) {
		return !(i%2);
	}).reduce(function  (a,b) {
		return a+b;
	});
}

console.log(filterEvenSum([1,2,3,4])); //<= 4

Main Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

javascript prototype

Understanding javascript prototype

Every object in javascript has got a prototype method which basically adds new methods to the base object which then can be called on instance objects.

Comparing with other languages , constructor functions are classes and the properties of the prototype (i.e. of the object referenced by the constructor function’s prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object’s fields are instance-specific and therefore added to the object itself during construction.

A simple example

Type this in Chrome Devtools console :

function Animal() {} // This is a first class functional object
Animal.prototype.speak = function() { console.log('OK'); } //Add a prototype function
var cat = new Animal(); //Creates a new Animal
cat.speak(); // Will call that function and print OK

In the above example we first defined the constructor function and then added speak function to it.
We then initialized cat as an Animal and called the that function on it.

Another Example

//Define a functional object to hold Animal
var Animal = function(name) {
    this.name = name;
};

//A new getter for that name
Animal.prototype.getName = function() {
    return this.name;
};

//Create a new object of type Animal
var cat = new Animal("Kitty");

//alert(cat.getName()); will use the getter

//This is where we add the speak function to Animal
Animal.prototype.speak = function() {
    alert('Hello, my name is ' + this.getName());
};

//Call the new method on cat
cat.speak();

When you will run the above code in devtools console , you will get an alert saying My name is Kitty.
In the above example , we created the instance object then added a method to the base , and then called the new method on the instance object.
This is how Inheritance works in javascript.

Sources :

http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work

http://ejohn.org/apps/learn/#65

splice javascript

javascript splice method.

The splice() method of Array in javascript changes the content of an array, adding new elements while removing old elements.
If you specify a different number of elements to insert than the number you’re removing, the array will have a different length at the end of the call.

The Syntax is

array.splice(index , howMany[, element1[, ...[, elementN]]])

where

index : Index at which to start changing the array. If greater than the length of the array, no elements will be added or removed. If negative, will begin that many elements from the end.

howMany : An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If howMany is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.

element1, …, elementN : The elements to add to the array. If you don’t specify any elements, splice simply removes elements from the array.

This method returns an array containing the removed elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Example Usages of .splice :-

1.To prepend an element at the start of an array.

Type this in your Devtools console

var array = [1,2,3,4] //We define the initial array
->undefined
array.splice(0,0,5) //index is 0, howmany is 0 and element is 5
->[]
array
->[5, 1, 2, 3, 4]
array.splice(0,0,6,7)//You can prepend n elements
->[6, 7, 5, 1, 2, 3, 4]

2.To remove the first element of an array.

To remove the first element from array ,

array.splice(0,1)

Type this in Devtools console :

array = [1,2,3,4]
->[1, 2, 3, 4]
array.splice(0,1)
->[1]
array
->[2, 3, 4]

Similarly to remove n elements from the start of an array :

array.splice(0,n)//n is no. of elems

3.Add and Remove elements from array

Let assume we want to add as well as remove elements from array at the same time
Consider code :
cities.splice(2,1,"Mumbai","Nagpur")

The index is 2 i.e. the 3rd element,
howmany is 1 ,i.e 1 element will be removed ,
“Mumbai”,”Nagpur” will get added at index 2.

Type this in console :-

var cities = ["Pune", "Bangalore", "Delhi", "Kolkata"]
->undefined
cities.splice(2,1,"Mumbai","Nagpur")
->["Delhi"]
cities
->["Pune", "Bangalore", "Mumbai", "Nagpur", "Kolkata"]

Sources

MDN splice