JavaScript – Make Custom Functions with Prototype

In the current article, I will show you how to build functions for built-in objects in JavaScript. The way I know is using a prototype. Thus, I will create functions, giving us the last n values of an array or returning a capitalization of our string. It is useful and may save you some time.

JS

The functions come one by one. With some explanations.


  • string.Capitalize()

This one is just one line of code. The idea is to return the string with the first letter capitalized. The built-in function toUpperCase() does the whole work:

String.prototype.capitalize = function(){
	return this.charAt(0).toUpperCase() + this.slice(1);
}

  • string.isBlank()

Not a science fiction again. It is a boolean function, telling us whether we have spaces before or after the string. It could be optimized, by using two returns and thus avoiding the if/else, but as far as it works OK, I will leave it as it is:

String.prototype.isBlank = function(){
	var result = this.trim();
	if (result.length>0){
		result = false;
	} else {
		result = true;
	}
	return result
}

  • string.words()

This function returns a list of the string values, separated by one or more spaces. RegEx is used:

String.prototype.words = function(){

	return this.split(/[ ]{1,}/);
}

  • string.format()

This is indeed a valuable function. It does something, that is granted in languages such as C#. Anyway, now we have it in JavaScript as well:

String.prototype.format = function(dict) {
  var result = this;

  if(typeof(dict) === "object") {
    Object.keys(dict).forEach(function(key) {
      result = result.replace("{" + key + "}", dict[key]);
    });
    return result;
  }

  var args = [];
  var n = arguments.length;
  var i = 0;

  for(i; i < n; i+=1) {
    args.push(arguments[i]);
  }

  args.forEach(function(arg) {
    result = result.replace("{}", arg);
  });

  return result;
}

  • array.head() and array.tail()

These two functions return the first or the last element of an array. Also available in C#, now in JS 🙂

Array.prototype.head = function(){
	return this[0];
}


Array.prototype.tail = function(){
	var mirror = this
	var result = mirror.shift();
	return this;
}

  • array.range()

Ever dreamt to build an array of numbers with a small function? Now it is available in JS:

Array.prototype.range = function(iStart,iEnd){
	var newRange = [];

	for (var i = iStart; i <= iEnd; i++) {
		newRange.push(i);
	};
	return newRange
}

  • array.sum()

Summing an array in JS is as easy as in Python now. Enjoy it:

Array.prototype.sum = function(myArray){
	var myResult = 0;

	var n = this.length;
	var i = 0;

	for(i; i < n; i+=1) {
		myResult += this[i];
	}

	return myResult;
}

  • array.product()

Multiplication of an array is not an issue any more:

Array.prototype.sum = function(myArray){
	var myResult = 0;

	var n = this.length;
	var i = 0;

	for(i; i < n; i+=1) {
		myResult += this[i];
	}

	return myResult;
}

  • array.compact()

This function simply clears away your array from all values, which are going to return false – e.g.[false, 0, ,null,undefined, NaN]. The array myForbidden is not used, it stays there as a reminder:

Array.prototype.compact = function(myArray){
	var myResult = [];
	var myForbidden = [false, 0, "",null,undefined, NaN];
	var n = this.length;
	var i = 0;

	for(i; i

  • array.take() and array.drop():

Taking the first N or the last N values of an array has never been easier in JS:

Array.prototype.take = function(firstN){
	var myResult = [];
	var i = 0;

	for (i; i

  • array.dedup()

Do you remember the set() in Python? Now we have something similar to it in JS:

Array.prototype.dedup = function(myArray){
	myResult = [];
	var n = this.length;
	var i = 0;
	
	for (i; i

  • array.sample()

Simply showing a random value from the array. Nothing more:

Array.prototype.sample = function(){
	var max = this.length-1;
	var min = 0;
	
	var myRandomPosition = Math.floor(Math.random()*(max-min+1)+min);
	return this[myRandomPosition];
}

That’s all folks! The whole code is available in my GitHub repo here. Enjoy it!