Skip to content
This repository has been archived by the owner on Jul 17, 2020. It is now read-only.

util.js

Zirak edited this page Dec 14, 2013 · 2 revisions

source/util.js is a mush of utility functions which extend native objects and their prototypes. This is their stories.

(Note on notation: Foo..bar means Foo.prototype.bar)

Object.merge(...args)

Shallow, non-mutative merge of the arguments.

var o0 = { a : 4, b : 5 },
    o1 = { a : 6, c : 7 };
Object.merge(o0, o1);
// { a : 6, b : 5, c : 7 }
// o0.a === 4

Object.iterate(obj, cb, thisArg)

Iterates over obj, calling cb.call(thisArg, key, value, obj).

var o = { a : 4, b : 5 };
Object.iterate(o, function (key, val, obj) {
    console.log(arguments);
});
// ["a", 4, { a : 4, b : 5}]
// ["b", 5, { a : 4, b : 5}]

Object.TruthMap(values)

Constructs a Truth Map, an object where each item in value is a key corresponding to true. Useful when making whitelists, blacklists, etc.

Object.TruthMap(['foo', 'bar']);
// { foo : true, bar : true }

Array.from(arrayLike)

Transforms arrayLike into a real array. Useful for NodeLists and arguments.

Array.from(document.getElementsByTagName('p')).map(...);

Array..invoke(funName, ...args)

Goes over each item in the array, invoking each item's function funName with args as arguments. If no such function exists on an item, it returns the item unchanged.

['hello', 'world'].invoke('toUpperCase');
// ['HELLO', 'WORLD']
[4, 9.482, Math.E].invoke('toFixed', 4)
// ['4.0000', '9.4820', '2.7183']

Array..first(cb)

Returns the first item in the array to pass cb. I believe this is the ES6 equivalent of Array..find.

Array..random()

Returns a random array item.

Array.forEach, Array.map, Array.filter, Array.reduce

ES5 does not define generic array methods on the Array object. Firefox does. Firefox was smarter.

Array.forEach('abc', console.log.bind(console));
// 'a' 0 'abc'
// 'b' 1 'abc'
// 'c' 2 'abc'

String..indexesOf(needle, startIndex)

Take a guess. Returns all indexes of needle. Did you guess?

String..supplant(obj)

String..supplant(...values)

A copy of Crockford's supplant (look for it in http://javascript.crockford.com/remedial.html), with the addition of a second overload which acts as if you supplied an array.

var data = { food : 'chicken finger', status : 'always missing' };
'{food}s are {status}'.supplant(data);
// 'chicken fingers are always missing'
'{0} and {1} sitting in a tree, K-I-L-L-I-N-G'.supplant('Tommy', 'Grim Reaper');
// 'Tommy and Grim Reaper sitting in a tree, K-I-L-L-I-N-G'

String..startsWith(needle)

Returns whether the subjects...wait for it..starts with needle.

Function..throttle(time)

Returns a function which, when called, will execute after time milliseconds. If called more than once within that span, the timer is reset.

Function..memoize()

Function memoizer. Do I have to explain everything around here!?

Function..memoizeAsync()

Uh, why is this here? Did I even test it?

Number..maxDecimal(places)

Returns the number with at most places digits after the dot.

Number..fallAfter(ranges)

This can probably be removed. Given that ranges is an ordered array of numbers, returns the number after which you can insert this without disrupting order.

4 .fallsAfter( [1, 2, 5] )
// 2
4 .fallsAfter( [0, 3] )
// 3

Math.ratio(a, b)

Returns the ratio a:b in string form. Uses gcd, described just below. Can probably be removed.

Math.gcd(a, b)

Returns the greatest common denominator using the Euclidean method. Can probably be removed.

Math.rand(min, max)

Returns a random number between min and max, inclusive.

Math.rand(max)

Equivalent to Math.rand(0, max)

Math.rand()

Equivalent to Math.rand(0, 9)

RegExp..toJSON()

RegExps are not proper JSON values, when you try and JSON.stringify them, it won't work. But now it will.

RegExp.escape(subject)

Escapes any special regexp characters in subject, so you can pass it into the RegExp constructor without fear.

Date.timeSince(before, after)

Returns the biggest whole interval between before and after, the largest unit being a year. If the difference between the two dates is 2 days and 4 hours, the function will return '2 days'.

Date.timeSince(before)

Equivalent to Date.timeSince(before, new Date())