Javascript Goodies

Everyone has their own Javascript file full of their trusty utilities. Here’s mine:

/*
 * A place for the handy things in life.
 */

"use strict";

//because I'm lazy
function l(arg) { console.log(arg); }

//like forEach, but for properties (useful when handling negative array indices)
Object.prototype.forAll = function(callback) {
	for(var p in this)
	{
		if(this.hasOwnProperty(p))
		{
			callback(this[p], p, this);
		}
	}
};

//runs a deep (recursive) clone to create a fully cloned object
Object.prototype.clone = function() {
	
	var o = this;
	var n;

	if(o instanceof Function)
	{
		n = function() { return o.apply(this, arguments); };
	}
	else
	{
		n = {};
	}

	//clone the properties and indices
	o.forAll(function(v, p) {
		if(v instanceof Object)
		{
			n[p] = v.clone();
		}
		else //primitive
		{
			n[p] = v;
		}
	});

	if(o.prototype)
	{
		n.prototype = o.prototype;
	}
	
	n.__proto__ = o.__proto__;

	return n;
}

//removes all descendants (faster than innerHTML = "")
HTMLElement.prototype.removeChildren = function() {
	while(this.firstChild)
	{
		this.removeChild(this.firstChild);
	}
};

//fix Javascript modulo bug for negative numbers... jeese...
Math.mod = function(x,n) { return(((x%n)+n)%n); };

//maps a value from one range to another (linear interpolation)
Math.map = function(x, in_min, in_max, out_min, out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; };

//clamps a number between two values (inclusive)
Number.prototype.clamp = function(min, max) { return Math.min(Math.max(this, min), max); };

//rounds floats to the specified number of decimals
Number.prototype.roundTo = function(d) {
  if(d === undefined) { d = 1; }
  d = Math.pow(10, d);
  return Math.round(this * d) / d;
};

//returns a different css color for as long as it can. Tweak to taste
//n = 0, 1, 2, 3...
function colorForIndex(n, s, l)
{
	var v = n * 282;
	v = Math.mod(v, 360);
	return "hsl(" + v.toString() + ", " + s.toString() + "%, " + l.toString() + "%)";
}

//see if this page has been referred to by another page
function referredFrom(page)
{
	if(document.referrer.search(page) !== -1) { return true; }
	return false;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s