Underscore.js in Visual Studio Code, working with collections – part 1

Working with collections part 1

each

Signature : _.each(list, iteratee)

Iterates over a list of elements, yielding each in turn to an iteratee function.

Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee‘s arguments will be (value, key, list). Returns the list for chaining.

Example :

var _ = require('underscore');

var myFunction = function(element, index, list)
{
    console.log(`Element : ${element}, Index : ${index}, Element found by index : ${list[index]}`);
}

_.each(["Apple", "Banana", "Grapefruit"], myFunction);

_.each({one: "Apple", two : "Banana", three : "Grapefruit"}, myFunction);

Output :

map

Signature : _.map(list, iteratee)

Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.

Example :

var _ = require('underscore');

var value = _.map([10, 20, 30], function(element) {
   return element * 10;
});
console.log(value);

value = _.map({one: 10, two : 20, three : 30}, function(element, key) {
    return element * 5;
});
console.log(value);

Output :

reduce

Signature : _.reduce(list, iteratee,[memo])

Reduce boils down a list of values into a single value.Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed four arguments: the memo, then the value and index (or key) of the iteration, and finally a reference to the entire list.

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

Example : 

var _ = require('underscore');

var value = _.reduce(["Apple", "Banana", "Grapefruit"], function(memo, value, index) {
    if (index == 0)
        return`I love ${value}`;
    else
        return`${memo} and ${value}`;
},"");
console.log(value);

Output :

reduceRight

Signature : _.reduceRight(list, iteratee,[memo])

The right-associative version of reduce.

Example : 

var _ = require('underscore');

var value = _.reduceRight(["Apple", "Banana", "Grapefruit"], function(memo, value, index, list) {
    if (index==list.length-1)
        return`I love ${value}`;
    else
        return`${memo} and ${value}`;
},"");

console.log(value);

Output :

find

Signature : _.find(list, iteratee)

Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn’t traverse the entire list.

Example :

var _ = require('underscore');

var value = _.find(["Apple", "Banana", "Grapefruit"], function(value) {
    return value.indexOf("p") >0;
});
console.log(value);

Output :

filter

Signature : _.filter(list, iteratee)

Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).

Example :

var _ = require('underscore');

var value = _.filter(["Apple", "Banana", "Grapefruit"], function(value) {
    return value.indexOf("p") >0;
});
console.log(value);

Output :

where

Signature : _.where(list, properties)

Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

Example :

var _ = require('underscore');

var listOfProducts = [
{country : "Canada", fruit : "Apple", color : "red"},
{country : "Canada", fruit : "Apple", color : "green"},
{country : "USA", fruit : "Grape", color : "yellow"},
{country : "USA", fruit : "Apple", color : "red"},
{country : "USA", fruit : "Lemon", color : "yellow"},
{country : "USA", fruit : "Lemon", color : "green"},
{country : "France", fruit : "Grape", color : "black"},
{country : "France", fruit : "Grape", color : "green"},
{country : "France", fruit : "Apple", color : "yellow"}
];

var value = _.where(listOfProducts, {country : "USA", fruit : "Lemon"});
console.log(value);

Output :

findWhere

Signature : _.reduceRight(list, properties)

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

Example :

var _ = require('underscore');

var listOfProducts = [
    {country : "Canada", fruit : "Apple", color : "red"},
    {country : "Canada", fruit : "Apple", color : "green"},
    {country : "USA", fruit : "Grape", color : "yellow"},
    {country : "USA", fruit : "Apple", color : "red"},
    {country : "USA", fruit : "Lemon", color : "yellow"},
    {country : "USA", fruit : "Lemon", color : "green"},
    {country : "France", fruit : "Grape", color : "black"},
    {country : "France", fruit : "Grape", color : "green"},
    {country : "France", fruit : "Apple", color : "yellow"}
];

var value = _.findWhere(listOfProducts, {color : "yellow"});
console.log(value);

Output :

Introducing Underscore.js: A Javascript helpers library, installation installation Visual Studio Code

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

Underscore provides over 100 functions that support both your favorite workaday functional helpers: mapfilterinvoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

Underscore allows to work with collections, arrays, objects, functions, and provides other utilities

How to install it?

Visual Studio Code using NPM:

npm install underscore

Visual Studio using Bower

bower install underscore

You can also simply download it here and include it in your Html pages.

Examples given in next serie of articles require Visual Studio code, Node.js (and NPM)

Let’s start with collections : Underscore.js, working with collections – part 1

WallabyJs, a smart unit tests runner!

Wallaby.js is a smart runner JavaScript tests and it’s super fast, it runs continuously your tests.

It reports the results directly into your code editor immediately when you change your code, we take example by Visual Studio 2.1 and the Jasmine framework for testing.

Step 1: Install WallabyJs

In our case, we’ll use Visual Studio 2013 to download the addon for Visual Studio WallabyJs here.

Caution : must have at least 4 update for Visual Studio 2013 to be compatible.

Step 2: Configuring WallabyJs

To set the execution environment of WallabyJs, configure three things:

– The path to the JavaScript files functions you want to test

– The path to the Javascript test files

– Javascript framework you want to use (WallabyJs supports Jasmine, Mocha, QUnit)

To do so we must create a json file to the root of your web project, I recommend naming like this: wallaby-jasmine.json, this will visually easily identify our configuration file :

{ 
   "files": [ "Scripts/*.js" ], 
   "tests": [ "Scripts/tests/*.spec.js" ], 
   "testFramework": "jasmine@2.1.3" 
}

The properties “files” and “tests” are arrays, you can put as many files as you want to test, “files” for files containing the test, “tests” for files of unit tests to execute.

You can also select with * all files in a directory you want.

Finally, the framework used in the latest WallabyJs Jasmine is version 2.1.3, you can check here syntax Jasmine.js 2.1 here: http://jasmine.github.io/2.1/introduction.html

Note: With the Framework Jasmine, the name of test file must end with .spec.js

Overview of web project:

Conversion.js (library to be tested)

var Conversion = { 
   livreVersKilo: function (livres) { 
      if (isNaN(livres)) { 
         throw "ValeurLivreIncorrecte"; 
      } 
      return livres / 2.2; 
   } 
};

conversion.spec.js (fichier de tests)

/// <reference path="../conversion.js" /> 
// Specs 
describe("The conversion library", function () { 
   describe("Pound to kilogram conversion", function () { 
      it("Should multiply the number of pounds per 2.2", function () { 
         expect(Conversion.livreVersKilo(22)).toBe(10); 
      }); 
      it("Should not multiply the number of pounds per 2.2", function () { 
         expect(Conversion.livreVersKilo(22)).not.toBe(9); 
      }); 
      it("Should throw an exception if the input is not numeric", function () { 
         var foo = function () { 
            Conversion.livreVersKilo("abc"); 
         }; 
         expect(foo).toThrow("ValeurLivreIncorrecte"); 
      }); 
      it("Should throw an exception if the input is not numeric", function () { 
         var foo = function () { 
            Conversion.livreVersKilo("1"); 
         }; 
         expect(foo).toThrow("ValeurLivreIncorrecte"); 
      }); 
   }); 
});

cap9

Step 3: Start Wallaby Js
To do this, stand on the wallaby-jasmine.json file, right-click and do “Start WallabyJs” :

cap2

If the boot fails, you will be notified in this case to verify the information your configuration file, otherwise if successful the following message:

cap3

From the start, WallabyJs will execute unit tests, the files tests will show green or red square (+ red message on failure) based on the test results:

cap6

Step 4: Add, edit tests

Once you edit your files from unit tests, WallabyJs will restart the tests without any action from you, same as you change your Javascript functions to be tested, WallabyJs will detect this and will also run unit tests.

To see a demo of WalabyJs in action watch the video here

Bonus for those with ReSharper :

Happy owners of ReSharper will be able to enjoy an additional feature:

Indeed other icons will appear in your test files, much like NCrunch, it is possible to launch the unit test in windowed mode :

cap7

cap8

So, what do you think? 🙂

Important detail : it’s not free unfortunately!

For the price, it’s here.