Underscore - Js Examples
Underscore - Js Examples
JS EXAMPLES
A QUICK GUIDE OF UNDERSCORE THROUGH EXAMPLES TO GET YOU STARTED WORKING WITH UNDERSCORE WRITTEN BY: TORE AURSTAD, SYSTEM DEVELOPER FROM NORWAY, 2013
1
UNDERSCORE.JS
UNDERSCORE.JS IS A JAVASCRIPT LIBRARY, WRITTEN PRIMARILY FOR ARRAY MANIPULATION BUT ALSO A LOT OF OTHER USAGES. THE VERSION TESTED WHEN WRITING THESE SLIDES IS 1.5.0 AND THIS VERSION CONTAINS 109 FUNCTIONS IN ALL. UNDERSCORE.JS TESTED HERE PRIMARILY WITH HTTP://JSBIN.COM IN MOZILLA FIREFOX, THIS IS THE OUTPUT YOU GET WHEN YOU ASK FOR THE FUNCTIONS IN UNDERSCORE:
console.log(_.functions(_)); ["after", "all", "any", "bind", "bindAll", "chain", "clone", "collect", "compact", "compose", "contains", "countBy", "debounce", "defaults", "defer", "delay", "detect", "difference", "drop", "each", "escape", "every", "extend", "filter", "find", "findWhere", "first", "flatten", "foldl", "foldr", "forEach", "functions", "groupBy", "has", "head", "identity", "include", "indexOf", "initial", "inject", "intersection", "invert", "invoke", "isArguments", "isArray", "isBoolean", "isDate", "isElement", "isEmpty", "isEqual", "isFinite", "isFunction", "isNaN", "isNull", "isNumber", "isObject", "isRegExp", "isString", "isUndefined", "keys", "last", "lastIndexOf", "map", "max", "memoize", "methods", "min", "mixin", "noConflict", "object", "omit", "once", "pairs", "partial", "pick", "pluck", "random", "range", "reduce", "reduceRight", "reject", "rest", "result", "select", "shuffle", "size", "some", "sortAscending", "sortBy", "sortDescending", "sortedIndex", "tail", "take", "tap", "template", "throttle", "times", "toArray", "unescape", "union", "uniq", "unique", "uniqueId", "unzip", "values", "where", "without", "wrap", "zip"]
BACKGROUND INFORMATION
WEBSITE OF UNDERSCORE.JS IS: http://underscorejs.org/ SOURCE CODE IS AVAILABLE ON GITHUB HERE: https://github.com/jashkenas/underscore UNDERSCORE.JS WAS CREATED BY JEREMY ASHKENAS IN 2009. CREATOR IS A WORLD RENOWNED PRODUCTIVE DEVELOPER, WORKING IN THE INTERACTIVE DIVISON OF NEW YORK TIMES.
Lets look at how we can use some element operators on arrays in JS next. We create a simple list of numbers to use when looking at element
operators in Underscore.Js
4
var nums = [ -1, 8, 8, 2, 9, 13, 16, 63 ]; _(nums).first(); //get the first item: -1 Similar to First() in LINQ _(nums).last(); //get the last item: 63 Similar to Last() in LINQ Note: you can pass in a number to specify the n number of items to retrieve
of the first and last items as an overload here
5
var stateRegion = [ { State: 'South-Trondelag', Region: 'Central' }, { State: 'Oslo', Region: 'Eastern' },
Map continued
var getRegionOfState = function(state){ return _.chain(stateRegion).where({ State: state}).pluck('Region').first().value(); } var norwegianCities = [ { City: 'Trondheim', State: 'South-Trondelag' }, { City: 'Oslo', State: 'Oslo' }, { City: 'Lillehammer', State: 'Oppland' }, { City: 'Bergen', State: 'Hordaland'}];
var norwegianCitiesWithRegion = _.map(norwegianCities, function(nc){ return { City: nc.City, State: nc.State, Region: getRegionOfState(nc.State) }; });
7
console.log(norwegianCitiesWithRegion);
This mapped array results in the following array: We can see that the mapped array now not only
was retrieved with the method in the previous sample.
Lets look at Reduce next. Lets count the number of cities with Region
Eastern.
8
Reduce
var norwegianCitiesInEasterRegion = _.reduce(norwegianCitiesWithRegion, function (memo, ncr) { return memo + ((ncr.Region == "Eastern") ? 1 : 0); }, 0); console.log(norwegianCitiesInEasterRegion);
We get the answer of 2 cities in the Eastern region of Norway. Please note that in the example above, we use Reduce together with
complex properties. To get a scalar into the memo parameter, it was necessary to set 0 as the third parameter of Reduce as the context parameter. For scalar arrays, this third parameter is not always required.
9
Projection operators
Projection is available in Underscore.js with projection operators pluck and pick. The operator pluck projects a single property, and pick can project multiple properties. This is similar to the Select operator in LINQ. console.log(_.pluck(norwegianCitiesWithRegion, "City")); //pluck gives: ["Trondheim", "Oslo", "Lillehammer", "Bergen"] The pick operator works on an individual basis on items in arrays. This is how we can use it for example: console.log(_.map(norwegianCitiesWithRegion, function(ncr){ return _.pick(ncr, "City", "Region"); }));
10
groupBy in Underscore.js
11
We can search for items in an array with a property of given value as in the
following example:
console.log(_.where(norwegianCitiesWithRegion, { Region: Eastern })); We get the two cities in our array matching the condition. We could have
passed in multiple property conditions here.
12
This object can then display its data for example in the following manner:
for(var c in cr){
console.log(c + ": " + cr[c]);
This gives the following output of the number of cities in each region in our sample:
[0, 2, 4, 6, 8] //Note stop value is not inclusive here either and that the step length is set to 2
14
Similar in function as OrderBy in LINQ Allows to sort an array. Specify which property to sort after. Possible to pass in sorting logic function also, or multiple properties to sort
with. Simple example next of single property sorting:
sortBy operator
_.sortBy(norwegianCitiesWithRegion, "City"); Descending sort on an array like in LINQ OrderByDescending can be done
using the reverse() function on an array (built in JS function).
_.sortBy(norwegianCitiesWithRegion, "City").reverse();
15
Returns: [3, 9, 12, 21] //all numbers in the passed in array that is divisible by 3
The contains operator returns true if the array contains the specified value. console.log("Contains 25?: " + _.contains([1,3,16,25,44], 25)); "Contains 25?: true"
16
Object operator
Different from Underscore.Js multiple array manipulation operators or functions, the object operator allows you to create objects with keys and values specified in two separate arrays, example next shows how to use this:
var mergedObject = _.object([ "Trondheim", "Oslo", "Lillehammer", "Bergen" ], [ "South-Trondelag", "Oslo", "Oppland", "Hordaland" ])
Object {Trondheim: "South-Trondelag", Oslo: "Oslo", Lillehammer: "Oppland", Bergen: "Hordaland"}
The ordering in these two lists counts. The first item in the first list is paired with the first item in the second list, then moving on to the second item in both lists and so on.
Underscore.Js has multiple utility functions and is therefore in many ways a general purpose utility library that fills in the missing gaps that pure Javascript can not fix
17
_.union([2,4,3,6,1],[7,8,2,4]); [2, 4, 3, 6, 1, 7, 8]
_.intersection([2,4,3,6,1],[7,8,2,4]); [2, 4]
18
_.difference([2,4,3,6,1],[7,8,2,4]); [3, 6, 1] The operator without is similar to the operator difference, but the second
part of the argument are values and not a single array to use for the exclusion.
_.difference([2,4,3,6,1],7,8,2,4); [3, 6, 1] //same results as above, but that was because we used the same
exclusion values and not an array
19
onceFunc() Listen very carefully, I shall say this only once. onceFunc() //will give no output this second time (or any time later)
20
Calling fibonacci with the same argument for n, will return the same cached
result instead of doing the calculation. Memoizing only happens with the exact same arguments here.
22
_.delay(function(){ console.log("hi") }, 1000); hi //this executes after 1 second is passed The special utility function defer executes a function in a non-blocking
fashion for the UI thread, waiting for the call stack to clear.
Object functions
There are more object functions in Underscore.js! The functions keys and
values can extract property names and values of properties of an object.
_.keys({ "City": "Trondheim", "State": "South Trondelag" }) ["City", "State"] _.values({ "City": "Trondheim", "State": "South Trondelag" }) ["Trondheim", "South Trondelag"] The keys function can be used to find column headers and values will
retrieve column values for each object, i.e. the row. In other words, an array of objects in Javascript can be displayed using these two methods in tabular form, usually with the _.each method or similar. 25
To do a complex equality comparison (not checking reference but that two objects have the same content), use isEqual
console.log(_.isEqual([1,2,3,4,17], [1,2,3,4,17])); Returns: true This was a simple example, but we can also compare complex objects with arbitrary level of nesting
To check if an object is a DOM element, use isElement: console.log("Object is DOM element: " + _.isElement(jQuery('body')[0])); Returns: Object is DOM element: true
26
The some function is aliased to any and is similar to LINQ any in functionality.
The every function is aliased to all and is similar to LINQ all in functionality.
We have already seen chain in action: { State: 'South-Trondelag', Region: 'Central' }, var stateRegion = [
console.log(_.random(0,100)); Returns random number between 0 and 100. The min and max values here are inclusive.
30
The each operator iterates over an array an performs a given iterator function. Example:
4
9 We can of course define the array before running the each operator / function.
Aliased to forEach
31
console.log(_.isFinite(102));
Returns true console.log(_.isRegExp(/moe/)); Returns true: This can be done to validate a regular expression that is being created for correct syntax console.log(_.isDate(new Date())); Returns true console.log(_.isDate("12. september 2013")); Returns false: wrong syntax this operator can validate a Date for correct syntax
32
Summary
Underscore.js has many different uses. It is impressive that the source code is only about 1250 lines of code for the
current version (1.5.0) and still has so many different uses
This shows how powerful Javascript can be and how compact it is The library is primarily a utility library. It is similar to a Swiss-army knife,
there are several uses, primarily focused on array manipulation.
We havent even covered the template support yet and to discover more,
check out the annotated source code of Underscore.js.
34
Thats all folks!! You might also want to check out these JS frameworks:
35