Useful JavaScript Extensions
Over the years I’ve collected a set of useful extensions to the Object, Array, and String constructs in JavaScript and I thought I might publish them. They are all pretty simple but it’s a pain to have to write these over and over for each new project so I just compiled them into on file and off we go. There are probably improvements that could be made to these methods and new ones to be added so please feel free to share your ideas and I’ll incorporate them back in.
Here is a listing of all the methods that this file adds:
ObjUtil.isString(Object)
ObjUtil.isNumber(Object)
ObjUtil.isBoolean(Object)
ObjUtil.isArray(Object)
Object.isFunc(Object)
ObjUtil.isDate(Object)
ObjUtil.isRegEx(Object)
ObjUtil.addOverload(Object, String, Function)
This function adds some pseudo function overloading to JavaScript. The first argument is the name of the function you’d like to expose and the second is the function to be called using that name. The limitation here is that the only way to distinguish between method implementations is by the number of arguments (JavaScript does not discriminate by type or name). Thanks to John Resig for the inspiration for this method.
var obj = { }; obj.addOverload("doSomething", function(a) { ... }); obj.addOverload("doSomething", function(a, b) { ... }); obj.doSomething(a); obj.doSomething(a, b);
ObjUtil.compareTo(Object, Object)
A generic comparison method that can be used in sorting functions. Handles differences in lexicographical order of strings by converting to lower case.
Function.partial()
Adds partial function capability through simple currying. Thanks to Oliver Steele’s Functional.js library for this method.
var add = function(a, b, c) { return a + b + c; }; var addPart = add.partial(1, undefined, 3); alert(addPart(2)); // alerts 6
String.toBoolean()
Converts the following values to true/false: “true” or “1″.
Array.copy()
Copies an array’s contents to a new array. Keep in mind that if the array isn’t made of simple types like string, number, or boolean that the new array will contain references to the old array’s objects. However, using the copy facilitates sorting and other mutations without affecting the original array.
Array.forEach(Function)
Takes a in a function and calls that function once for every item in the array.
var arr = [1,2,3]; arr.forEach(function(i) { alert(i); });
Array.find(Function)
Takes a function that returns a boolean and returns the item that matches the functions criteria. If more than one item match the first one is returned.
var arr = [{name:"Bill", age:17}, {name:"Bob", age:27}, {name:"Brian", age:34}]; var item = arr.find(function(i) { return i.name == "Bob"; });
Array.findAll(Function)
Takes a function that returns a boolean and returns an array of all items matching the functions criteria.
var arr = [{name:"Bill", age:17}, {name:"Bob", age:27}, {name:"Brian", age:34}]; var items = arr.findAll(function(i) { return i.age > 25; });
Array.contains(Object)
Tests if an array contains a certain item, returns a boolean.
Array.distinct()
Returns a new array of distinct values from the source array.
Array.min()
Returns the minimum alpha-numeric value in the array.
Array.max()
Returns the maximum alpha-numeric value in the array.
Array.first()
Returns the first item in an array or null if the array is empty.
Array.last()
Returns the last item in an array or null if the array is empty.
Array.sortAscending()
Sorts the array in ascending numerical or lexicographical order depending on if the first item in the array is a number or not.
Array.sortDescending()
Sorts the array in descending numerical or lexicographical order depending on if the first item in the array is a number or not.
Array.randomize()
Randomizes the order of the array.
Array.count(), Array.count(Function)
Returns the number of items in the array. If a function is passed in it counts the items matching the functions criteria.
var birds = [{name:"Bill", birdType:"ostrich"}, {name:"Bob", birdType:"penguin"}, {name:"Brian", birdType:"penguin"}]; var penguinCount = birds.count(function(i) { i.birdType == 'penguin'; });
Array.except(Array)
Takes two Array objects and returns a new array of only the items that are unique to both of the first two.
var arrA = [1,2,3,4,5]; var arrB = [3,4,5,6,7,8]; var itmes = arrA.except(arrB);
Array.intersect(Array)
Takes two Array objects and returns a new array of only the items shared between the first two.
var arrA = [1,2,3,4,5]; var arrB = [3,4,5,6,7,8]; var itmes = arrA.intersect(arrB);
Array.average()
Returns the average numeric value in the array.
Array.sum()
Returns the sum of the numeric values in the array.
Array.union(Array)
Returns a new array after joining two others but does not include duplicates.
var arrA = [1,2,3,4,5]; var arrB = [3,4,5,6,7,8]; var newArr = arrA.union(arrB);
Array.safePush(Object)
Adds an item to an array but only if that item doesn’t already exist in the array.
Array.getRandom()
Returns a random item from the array.
Array.insertAt(Number, Object)
Adds an item to an array at the specified position (first parameter).
Array.remove(Function)
Removes items matching the functions criteria from the array.
var arr = [{id:1, name:"Bob"}, {id:2, name:"Tom"}, {id:3, name:"Jim"}]; arr.remove(function(i) { return i.name == "Tom"; });
Array.indexOf(Object)
Returns the index of the item in the array or -1 if the item isn’t found.
Download JavaScriptExtensions.zip
Note: There is a “tests.html” file which contains examples and unit tests for all of these extensions. The unit tests are written for FireUnit for FireBug.
Category: JavaScript 3 comments »
February 22nd, 2009 at 12:49 pm
[...] JavaScript Events with the Observer PatternUseful JavaScript ExtensionsA Study in Patterns: The State PatternYou Can Never Go BackIntegrating Adobe Flex and .NET with [...]
April 15th, 2009 at 11:41 pm
If you have to do it, you might as well do it right
April 16th, 2009 at 8:51 am
Care to elaborate?