What is underscore.js?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. - Excerpts from http://underscorejs.org/
Lets unleash power of underscore.js
- You can download it from http://underscorejs.org/underscore.js
OR
- npm install underscore
- Use any editor to write HTML file, I prefer Sublime Text, but it's your choice
- Case study: There are many restaurants in City with different cuisines, menu items etc. Let's find desired output from what we want:
- <!DOCTYPE html>
- <html ng-app>
- <head>
- <script type='text/javascript' src='angular.js'></script>
- <script type='text/javascript' src='controller.js'></script>
- </head>
- <body>
- <script type='text/javascript'>
- var restaurant = [{
- 'id': '0',
- 'restaurantName': 'Indian Delight',
- 'street': '123, Street1, 1st Avenue',
- 'menu': [{
- 'Roti': '5',
- 'Dal': '10',
- 'Veggies': '20'
- }]
- },
- {
- 'id': '1',
- 'restaurantName': 'Chinese Hut',
- 'street': '456, Street2, 2nd Avenue',
- 'menu': [{
- 'Dimsum': '10',
- 'Momos': '20',
- 'Soup': '15'
- }]
- },
- {
- 'id': '2',
- 'restaurantName': 'Italian Bistro',
- 'street': '789, 5th Block, 3rd Avenue',
- 'menu': [{
- 'Pasta': 15,
- 'Pizza': 20,
- 'Salad': 5
- }]
- }
- ]
- function GetAllRestaurant() {
- console.log(_.pluck(restaurant, 'restaurantName'));
- }
- function RestaurantTotalMenuItemPrice(id) {
- var RestaurantMenu = _.pluck(restaurant, 'menu')[id];
- //Find RestaurantMenu by passing id
- //output is object > [...]
- //sum prices of all items, therefore we'll get all values from Key Pair
- var prices = _.values(RestaurantMenu[0]);
- //now reduce values to sum
- var sum = _.reduce(prices, function(memo, num) { return memo + num; })
- console.log(sum);
- }
- function TotalRestaurant() {
- console.log(_.size(restaurant));
- }
- GetAllRestaurant(); //output : ["Indian Delight", "Chinese Hut", "Italian Bistro"]
- RestaurantTotalMenuItemPrice(2); //output : 40
- TotalRestaurant(); //output : 3
- </script>
- </div>
- </body>
- </html>
Guest UserPosted Jun 30, 2014, 9:28 PM
Thanks DJ & Sanjay!!!
Sanjay SinghPosted Jun 30, 2014, 2:25 PM
nice explanation
Former memberPosted Jun 30, 2014, 7:42 AM
It is nice blog post !
Guest UserPosted Jun 29, 2014, 11:58 PM
sure Mahesh!
Mahesh ChandPosted Jun 29, 2014, 12:30 PM
Welcome aboard :). You can post these as articles with little more description. We are planning to merge both Articles and Blogs. Some people are confused about Articles vs. Blogs.