New MooTools Methods: .from()

By  on  

MooTools 1.3 beta 2 was recently released and you may see a few new methods implemented to String, Array, Number, and Function: from. The from method of each of those Types returns an object of that type. Simply put: you'll always receive back an object of that type based on what you give it.

The New Method Code

Function.from = function(item){
	return (typeOf(item) == 'function') ? item : function(){
		return item;
	};
};

Array.from = function(item){
	if (item == null) return [];
	return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : Array.prototype.slice.call(item) : [item];
};

Number.from = function(item){
	var number = parseFloat(item);
	return isFinite(number) ? number : null;
};

String.from = function(item){
	return item + '';
};

The from method is added to String, Array, Number, and Function natives. Enough with the underlying code though -- examples are easier to understand.

Function.from, Array.from, Number.from, String.from Examples

Array.from('Item');
//returns ['Item'] (array type)

Function.from('Item, Whoa, Hey');
//returns function() { return 'Item, Whoa', Hey'; } (function type)

String.from(function() { alert('MooTools FTW!'); });
//returns function () { alert("MooTools FTW!"); } (string type)

Number.from('8765309');
//returns 8765309 (number type)

Each example above shows you what's returned by each method. Being able to generate a given object type from any argument using from can save you a lot of time -- especially when a given MooTools class or method requires an argument of a specific type. from is just another example of how MooTools can make your JavaScript life easier!

Recent Features

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

Discussion

  1. Oh great! :)

    nomore switch-cases for specific type argument…
    Life is really easier with MooTools

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!