JAVA SCRIPT - Utilizing the Utility Library Underscore - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Utilizing the Utility Library Underscore - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, January 2, 2019

JAVA SCRIPT - Utilizing the Utility Library Underscore

Utilizing the Utility Library Underscore


Problem

You want a simple-to-use, basic utility library that can be used with your applications or in combination with other more complex frameworks like jQuery

Solution

Use the increasingly ubiquitous Underscore.js library. It can be downloaded, installed using npm or Bower, or accessed via CDN:
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js">
</script>

I demonstrated memoization with a Fibonacci. With Underscore.js, my job is greatly simplified


var fibonacci = _.memoize(function(n) {
 return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});
console.log(fibonacci(10)); // 55

EXPLAIN

Underscore.js provides various functions categorized as: 

• Collections 
• Arrays 
• Functions 
• Objects 
• Utility 
• Chaining 

Underscore.js enhances existing JavaScript capability, but does so without extending the prototype object, which could make the library incompatible with other libraries or your own application. The utility’s functionality is accessible via the underscore (_) character, hence the name. However, if you use it with another library that also uses the underscore, you can remove the conflict: 


var underscore = _.noConflict();

The solution demonstrated the _.memoize() functionality. The following code dem‐ onstrates just a sampling of some of the other functionality:

// flatten a multidimensional array
var ary = _.flatten([1, ['apple'], [3, [['peach']]]]);
console.log(ary); // [1, "apple", 3, "peach"]
// filter an object based on an array of blacklisted keys
var fltobj = _.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
console.log(fltobj); // [object Object] { age: 50, name: "moe'}
// escape a string for insertion into HTML
var str = _.escape("
This & that and 'the other'
"); console.log(str); // "<div>This & that and 'the other'</div>"

No comments:

Post a Comment

Post Top Ad