Functional Programming in JavaScript Notes (Array map & filter)

Categories: JavaScript; Tagged with: ; @ November 20th, 2014 23:35

Array.Map:

Array.prototype.map = function(projectionFunction) {
     var results = [];
     this.forEach(function(itemInArray) {

        // ------------ INSERT CODE HERE! ----------------------------
         // Apply the projectionFunction to each item in the array and add
         // each result to the results array.
         // Note: you can add items to an array with the push() method.
         // ------------ INSERT CODE HERE! ----------------------------
     results.push(projectionFunction(itemInArray));

    });

    return results;
};

// JSON.stringify([1,2,3].map(function(x) { return x + 1; })) === '[2,3,4]'

Array.filter

Array.prototype.filter = function(predicateFunction) {
     var results = [];
     this.forEach(function(itemInArray) {
         // ------------ INSERT CODE HERE! ----------------------------
         // Apply the predicateFunction to each item in the array. If the
         // result is truthy, add each result to the results array.
         // Note: remember you can add items to the array using the array's
         // push() method.
         // ------------ INSERT CODE HERE! ----------------------------
     if(predicateFunction(itemInArray)) {
        results.push(itemInArray);
     }
     });

    return results;
};

// JSON.stringify([1,2,3].filter(function(x) { return x > 2})) === "[3]"

Chaining call

function() {
     var newReleases = [
             {
                 "id": 70111470,
                 "title": "Die Hard",
                 "boxart": "http://cdn-0.nflximg.com/images/2891/DieHard.jpg",
                 "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                 "rating": 4.0,
                 "bookmark": []
             },
             {
                 "id": 654356453,
                 "title": "Bad Boys",
                 "boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
                 "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                 "rating": 5.0,
                 "bookmark": [{ id:432534, time:65876586 }]
             },
             {
                 "id": 65432445,
                 "title": "The Chamber",
                 "boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
                 "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                 "rating": 4.0,
                 "bookmark": []
             },
             {
                 "id": 675465,
                 "title": "Fracture",
                 "boxart": "http://cdn-0.nflximg.com/images/2891/Fracture.jpg",
                 "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                 "rating": 5.0,
                 "bookmark": [{ id:432534, time:65876586 }]
             }
         ];

    // ------------   INSERT CODE HERE!  -----------------------------------
     // Chain the filter and map functions to select the id of all videos
     // with a rating of 5.0.

    return newReleases.
         filter(function(video) {
             return video.rating === 5.0;
         }).
         map(function(video) {
             return video.id;
         });
     // ------------   INSERT CODE HERE!  -----------------------------------
}

JavaScript Day1: Java Script Objects

Categories: JavaScript; Tagged with: ; @ November 13th, 2014 22:57
  // define a flight
        var flight = {
            airline: "KLM",
            number: 835,
            departure: {
                city: "SG",
                IATA: "SIN"
            },
            scheduleDays: [1, 2, 5]
        };

        console.log("Flight: ", flight);

        // add new attribute
        flight.code="KLM835";
        console.log("Added code: ", flight);

        // retrieve attribute
        console.log("Retrieve departure city:", flight.departure.city);

        // delete attribute
        console.log("Flight code: ", flight.code);
        delete flight.code;
        console.log("Deleted flight code: ", flight.code);

        // for...in
        for(day in flight.scheduleDays) {
            console.log("for...in: schedule day: ", day);
        }

        // for loop
        for(i = 0; i < flight.scheduleDays.length; i++ ) {
            console.log("Schedule day:", flight.scheduleDays[i], " @ index: " , i);
        }

        // define new function
        var printFlight = function(flight) {
         return "Flight print: " +  flight.airline + " - " + flight.number;
        };

        // initialize new flight via prototype;
        var flight2 = Object.create(flight);
        console.log("Flight2 created based on Flight: " +  printFlight(flight2));

        // add new attribute to the new flight
        flight2.code = "KML836";
        console.log("Flight2.code: ", flight2.code);
        console.log("Flight.code: ", flight.code);

        // update new flight
        flight2.airline = "SIA";
        console.log("Flight.airline: ", flight.airline);
        console.log("Flight2 airline", flight2.airline);

        // update the prototype;
        flight.airline = "BA";
        console.log("Flight.airline: ", flight.airline);
        console.log("Flight2 airline", flight2.airline);

        // type of
        console.log(typeof flight);
        console.log(typeof flight2);
        console.log(typeof flight.scheduleDays[0]);

output:

Flight: 
Object {airline: "KLM", number: 835, departure: Object, scheduleDays: Array[3]}
Added code: 
Object {airline: "KLM", number: 835, departure: Object, scheduleDays: Array[3], code: "KLM835"}
Retrieve departure city: SG
Flight code:  KLM835
Deleted flight code:  undefined for...in: schedule day:  0 for...in: schedule day:  1 for...in: schedule day:  2 Schedule day: 1  @ index:  0 Schedule day: 2  @ index:  1 Schedule day: 5  @ index:  2 Flight2 created based on Flight: Flight print: KLM - 835
Flight2.code:  KML836 Flight.code:  undefined
flight.airline:  KLM Flight2 airline SIA Flight.airline:  BA
Flight2 airline SIA object object number

AngularJS For Dummies

Categories: JavaScript; Tagged with: ; @ November 26th, 2013 20:38

Overview

Why AngularJS?

MVC:  Template(Html with AngularJS expression), Controller(no need to extend anything, pure JS function);

Data Binding: Easy to display/update data;

Routing & Multiple Views: build deep linking single page application;

Dependance Injection;

Testing;

Quick Start

AngularJS  tutorial:  key features in example http://code.angularjs.org/1.0.8/docs/tutorial

Seed Project: https://github.com/angular/angular-seed
    Please note that the ‘Seed project’ may not using the latest stable version. so probably you need to change the AngularJS js lib.

App.js

config the application, set route mapping. for example:

// Declare app level module which depends on filters, and services
angular.module(‘demo-app’, [
  ‘demo-app.controllers’,
  ‘user.service’
]).
config([‘$routeProvider’, function($routeProvider) {
    $routeProvider.when(‘/user, {templateUrl: ‘partials/user/list.html’});
    $routeProvider.when(‘/user/show/:id’, {templateUrl: ‘partials/user/details.html’});
    $routeProvider.when(‘/script’, {templateUrl: ‘partials/script/list.html’, controller: ‘scriptListCtrl’});
    $routeProvider.otherwise({redirectTo: ‘/user’});
}]);

Module

    Modules declaratively specify how an application should be bootstrapped. http://docs.angularjs.org/guide/module

In the seed project, the application break down into multiple modules like: Services, Directives, filters, ect,.

Basically, a module have two kinds of blocks:  ‘Configuration blocks’ and ‘Run blocks’. the ‘config(…);’ in App.js is ‘Configuration block’.  one typical difference is: in ‘Configuration block’ only can inject ‘Providers’ cannot inject instances.

http://stackoverflow.com/questions/10486769/cannot-get-to-rootscope
Data binding

<h1>User- Name: {{user.name}}</h1>
    <div>
        <form novalidate class=”angularJSForm”>
            Name:
                <input type=”text” ng-model=”user.name” required /> <br />
        </form>
    </div>
</div>

‘user’ is the model, and this instance is live in a ‘Scope’, each page have it’s own scope automatically, scope can be injected into controller.
Controller

No need to extend any interface, AngularJS takes the responsibility of injection:

function userDetailsCtrl($scope, $routeParams, $http, UserEditorService) {
    $scope.action = $routeParams.action;
    $scope.id = $routeParams.id;

      …
      $scope.onJobClicked = function(job) {
        $scope.currentJob = job;
      };

      $scope.showOrHide = function(job) {
        return angular.equals($scope.currentJob, job);
    };
}

Note: UserEditorService is a Service, AngularJS will inject the instance of the service to the controller.

You may inject the controller to a template by configuring app.js or set inside the template:

Service

How to create service:

var module = angular.module(‘user.service’, []);

module.service(‘UserEditorService’, function() {
        this.user;

        this.user= function(user) {
            this.user= user;
            console.log(‘Service\’s user updated’);
        };

        this.getUser= function() {
            console.log(“Get User: ” + this.user+ “, ” + this.toString());
            return this.user;
        };
    }
);

How to share data between different controller?

– There’s a global scope in AngularJS, however, I don’t think it’s a good way to share data using global scope;

– using service: ‘UserEditorService’ in ‘userDetailsCtrl’

JavaScript test framework

Jasmine: http://pivotal.github.io/jasmine/
Jasmine Maven Plugin http://searls.github.io/jasmine-maven-plugin/

With the help of “Jasmine Maven Plugin”, we can invoke the JavaScript Unit tests from Maven. this plugin contains a web server, we can check the test result via. browser.

How to run Test cases in Jenkins/Linux?

Jasmine Maven Plugin uses PhantomJS/HtmlUnit to execute JavaScript test. http://searls.github.io/jasmine-maven-plugin/phantomjs.html

you may specific the browser by modifying pom.xml. http://searls.github.io/jasmine-maven-plugin/test-mojo.html#browserVersion

Configuration Properties for Jasmine Maven Pluginhttp://gotofritz.net/blog/geekery/configuration-jasmine-maven-plugin/

How to run test cases and get the results?

mvn jasmine:bdd

This goal will start a build-in server, you may get/modify the port from pom.xml. Open any browser, then you can get the results based on the browser you’re using.

LESS.js Hello world

Categories: JavaScript; Tagged with: ; @ November 6th, 2013 23:58

What is Less?

LESS extends CSS with dynamic behavior such asvariables, mixins, operations and functions.

Less Hello world

Style.less:

@header-color: #FFF000;
h1 {
  border: black dashed 2px;
  color: @header-color;
}

for more syntax or functions: http://lesscss.org/#reference

HTML:

<html>
<head>
    <title>Test-Liguoliang.com</title>
    <link rel="stylesheet/less" type="text/css" href="./css/src/style.less" />
    <script src="./lib/less/less-1.5.0.min.js" type="text/javascript"></script>

</head>
<body>

<h1>Header</h1>

</body>
</html>

IntelliJ Idea Less compiler plugin:

http://plugins.jetbrains.com/plugin/7059?pr=idea

The must-have plugin if you are using Less.js and IntelliJ!

what you need to do is install the plugin, and config it. after you finished, it’ll compile the .less to .css every time you modify the .less.

image

jQuery — Ajax Post数据乱码

Categories: JavaScript; Tagged with: ; @ April 20th, 2011 17:47

jQuery.ajax() API:

“POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.”  http://api.jquery.com/jQuery.ajax/

使用IE时, 出现乱码… 后台是java, tomcat的server.xml也已配置编码(见:RiaShanghai)….
突然发现用Firefox就木有问题.

“因为jquery ajax是使用utf-8来编码发送数据的,ie在发送时却没加上charset=utf-8,从而导致乱码(IE默认使用iso-8859-1编码)”http://fatkun.com/2010/12/jquery-ajax.html

呃, 应该就是这么个问题了.

解决方法:

$.ajaxSetup({ contentType: "application/x-www-form-urlencoded; charset=utf-8" });



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.