Functional Programming in JavaScript Notes (Array map & filter)

Categories: JavaScript 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 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

Java: Config slf4j and log4j in Maven Project

Categories: Java November 10th, 2014 23:29

1. Config Maven dependences


    <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-api</artifactId>         <version>1.7.7</version>     </dependency>
      <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-log4j12</artifactId>
       <version>1.7.7</version>
    </dependency>

2. Setup log4j configuration

src/main/resources/log4j.xml (log4j.properties):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
   <appender name="console" class="org.apache.log4j.ConsoleAppender">
     <param name="Target" value="System.out"/>
     <layout class="org.apache.log4j.PatternLayout">
       <param name="ConversionPattern" value="%d %-5p %c{1} - %m%n"/>
     </layout>
   </appender>

  <root>
     <priority value ="debug" />
     <appender-ref ref="console" />
   </root>
</log4j:configuration>

or log4j.properties

log4j.rootLogger=DEBUG, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

3. Initialize Logger and use it

package com.liguoliang.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogTest {

	static Logger LOGGER = LoggerFactory.getLogger(LogTest.class);
	
	public static void main(String[] args) {
		LOGGER.info("slf4j test info");
	}
}

output:

2014-11-10 23:07:39,624 INFO  LogTest - slf4j test info

Categories: 垃圾山 November 8th, 2014 15:52

日历上写着 winter begins,我猜是立冬了。

如果一年有四季,我最喜欢的是秋天。立冬意味着秋天即将结束,很快就要北风吹,雪花飘。我照旧忙碌在赤道附近绵绵无绝期的夏天里。 而我的家乡夏热冬凉,四季分明。

上次回家是在八月初,湿热的夏天, 晃悠了两周后,我开始盘算着什么时候回家找工作 买房子 娶媳妇这档子非办不可、皆大欢喜的事情。 飞机落地后纠结了几个小时,一觉睡过去,我决定继续随波逐流爱咋咋地。
紧接着去移民局拿了PR卡片。于是多了一个选择,但选择跟爱一样,都能可是潜在的痛苦。

但我还是喜欢秋天,清澈 凌烈 饱满 含蓄。冷气充足的办公室跟窗外飘摇的小树满足了我很多的幻想。这样的幻想让我短暂的活在虚构的季节里。 短短一生,不过几十个秋。

她说,你怎么还不更新?我说我跟你沉浸在生活里,没法探出头来看生活,没时间享受空虚寂寞,怎么能有空无病呻吟故做愁呢。
如果我会画画,一定要画一幅这样的照片,两人坐在秋天的午后,阳光透过所剩不多的树叶撒在身上,小风吹在背后,一地金黄的落叶跟着跑,两人安静的坐着,一言不发。

八月

Categories: 垃圾山 September 7th, 2014 15:21

呼和浩特

飞机落地后看到消息, 他们三个在出口的KFC等我。等我拖着行李往外走时,先是看到两个非常猥琐的胖子, 紧接着激动的跟这两个胖子一一握手(忘记有没有拥抱或者更亲密的接触), 三人嘻嘻哈哈的找到了另外一个胖子。 四个人便凑齐了。

临走时, 同事问我, 我的同学们在内蒙古 在中国做什么, 我说, 呃, 不太清楚,很少联系。 是的, 很少联系。

抛开婚姻,家庭, 七年的时间并没有让我们改变太多. 胖了一些, 成熟了一些.

草原

草原上的少年们还是那么的猥琐。 大口吃肉 大口喝酒, 半夜被冻醒,发现自己躺在冰冷坚硬的蒙古包里,摸索周围没有任何能盖的东西,于是卷了臭烘烘的地毯继续大睡。头疼,阵阵冷气从四周袭来,我不断的蜷缩着毯子,直觉告诉我毯子太薄,再拉就碎啦,说不定等下我就要冻死了,可惜我都不知道晚上发生了什么,为什么会睡在这里, 关键的问题是,那帮人去哪了?! 而且我也记不清楚下午带床的蒙古包在哪了。。。

不知过了多久,被人踢醒, 同学说再睡下去就要冻死了,于是我们哆哆嗦嗦的出了蒙古包,发现另外两个在车里开着暖风呼呼大睡。

第二天早晨,金灿灿的太阳射进蒙古包,头疼,于是换上衣服,在草原上跑了五公里,酒醒。

路过篝火盆子时,觉得眼熟。 后来朋友的朋友说,哎呀, 昨晚你们跳的可真欢呀!

羊肉

到内蒙的第一天,同学问,想来做什么? 大家都说吃肉喝酒。 于是顿顿酒肉,草原一夜后,同学再问吃什么时,“清淡, 清淡, 清淡!”

同学笑笑,你们太不耐操了, 两顿羊肉就把你们搞翻了。 // 高尚的人都是相似的,庸俗的人却各有各的庸俗。

如果没有你,日子怎么过

不知道在呼市的哪个角落, 听到了这首歌(如果没有你, 白光),在之后的日子里,在出租车上,烤肉摊子上,在黑夜的大路上,这首歌不是的蹦出来,从我的嘴里哼出来。同学受不了,推荐我听 我是你的小苹果, 试图用这首歌来给我洗脑,未果。

几天后,回到家,发现侄子会唱这首歌, 点了几次,于是脑子里装进了很多小苹果。 俗而不做。

拉扯

除了酒足饭饱之外, 回家还有另外一种强烈的感觉就是拉扯.

外面的世界跟家里的世界, 翻过前面的山继续走, 还是趟过后面的河回到家乡.

我在家乡挂念外面的世界, 却在异乡回忆家乡的情景.

Older Posts


Popular Tags

Archives


AD


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