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.
An alternative to the built in typeof
operator. This function is what the typeof operator should have been.
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
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
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"]);
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"
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'
Horizontally centers a block element, it has to have a specified width or it won't work.