Skip to content

Instantly share code, notes, and snippets.

@Azeirah
Last active August 29, 2015 14:01
Show Gist options
  • Save Azeirah/824be681efe3b9362c05 to your computer and use it in GitHub Desktop.
Save Azeirah/824be681efe3b9362c05 to your computer and use it in GitHub Desktop.
Javascript simple utilities script that I use often.
.center {
margin: 0 auto;
}
.center-text {
text-align: center;
}
var util = {};
util.toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
util.measureTime = function (func, arguments, count) {
window.performance = window.performance || {};
var maxCount = count || 500;
var start = performance.now();
var n;
this.name = "nothing";
for (n = 0; n < maxCount; n++) {
func.apply(undefined, arguments);
}
elapsed = performance.now() - start;
console.log("Average execution time is " + elapsed/maxCount + " ms");
};
util.listProperties = function (obj) {
var property;
var type = util.toType(obj);
for (var prop in obj) {
property = obj[prop];
if (util.toType(obj[prop]) !== "function") {
console.log("object [" + type + "]." + prop + ":");
console.log(property);
}
}
};
util.listFunctions = function (obj) {
var property;
var type = util.toType(obj);
for (var prop in obj) {
property = obj[prop];
if (util.toType(obj[prop]) === "function") {
console.log("object [" + type + "]." + prop + ":");
console.log(property);
}
}
};
util.format = function (str, args) {
var re = /\{([^}]+)\}/g;
return str.replace(re, function (_, match) {
return args[match];
});
};
util.padString = function (padCharacter, length, string) {
var padString = new String(length);
for (var i = 0; i < length; i++) {
padString += padCharacter;
}
return (padString + string).slice(-length);
};
util.elementSelector = function (obj) {
return obj === "string" ? document.querySelector(obj) : obj;
};
util.range = function () {
var arr = [];
if (arguments.length === 1) {
for (var i = 0; i < arguments[0]; i++) {
arr.push(i);
}
} else if (arguments.length === 2) {
for (var i = arguments[0]; i < arguments[1] + 1; i++) {
arr.push(i);
}
}
return arr;
};
util.translate = function translate(value, leftMin, leftMax, rightMin, rightMax) {
var leftSpan = leftMax - leftMin;
var rightSpan = rightMax - rightMin;
var scaled = (value - leftMin) / leftSpan;
if (isNaN(scaled)) {
return value;
}
return rightMin + scaled * rightSpan;
}
util.$ = function (queryString) {
return document.querySelector(queryString);
};
util.createElement = (element, cls, attributes) {
cls = cls || "";
attributes = attributes || {};
var element = document.createElement(element);
element.className = cls;
for (var attr in attributes) {
element.setAttribute(attr, attributes[attr]);
}
return element;
};

A simple web toolbelt

Over time, I commonly see myself using certain functions over and over again, I rewrite them for a lot of applications I create. So instead of having to rewrite them every time, I collect them in this gist.

JavaScript utility Functions

toType

An alternative to the built in typeof operator. This function is what the typeof operator should have been.

measureTime

measureTime is a simple way to measure the performance of any function. It takes 3 arguments.

  • func - required. The function to be called.

  • arguments - optional. The arguments to be passed to func, as an array.

  • count - optional. How many times the function should be called. Defaults to 500 times.

Example:

util.measureTime(function () {
  console.log('hello world!');
}, [], 5000);

// hello world
// ...
// hello world
// Average execution time is 0.06738060000059194 ms

listProperties

It prints out all non-function properties of an object.

example:

var obj = {
  count: function () {
    console.log("1, 2, 3, 4, 5");
  },
  read: true,
  amountOfApples: 5
};

util.listProperties(obj);
// object [object].read:
// true
// object [object].amountOfApples:
// 5 

format

Python style string formatting.

  • string The string you want to format. Use {n} where you want to insert something.
  • array An array of variables that will be inserted into the string. array[0] matches {0}, array[1] {1} and so on.

example:

util.format("I have {0} eyes, {0} legs and I have {1} hair.", [2, "a lot of"]);

padString

Fills your string with a character of choice up to the length you choose.

  • padCharacter, the character you want to pad your string with (note, if its length > 1, the composed string won't be of requested length)
  • length, how long you want your resulting string to be
  • string, the string you want to pad

Later, this method will be able to align your string to the right, left or center of your padding.

example:

padString("0", 2, "8") + ":"  + padString("0", 2, "43"); //  08:43"
padString(" ", 40, "hi"); // "                                      hi"

elementSelector

This function takes either an element or a selector string, and returns an element, this is nice for when you want function that can be passed either a selector or an element, and just want to do some DOM operations.

elementSelector("body") // returns the body element
var body = document.body;
elementSelector(body) // returns the body element

elementSelector(".container") // returns the first element with the class 'container'

Css utility classes

.center

Horizontally centers a block element, it has to have a specified width or it won't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment