Featured image of post JS函数式编程记录

JS函数式编程记录

JS函数式编程记录

第一部分 组合

组合

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var compose = function(f, g) {
    return function(x) {
        return f(g(x));
    };
};

var toUpperCase = function(x) { return x.toUpperCase(); };
var exclaim = function(x) { return x + '!'; };
var shout = compose(exclaim, toUpperCase);

let result = shout("send in the clowns");

实例应用

./index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>flickr</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js"></script>
    <script src="./flickr.js"></script>
</head>
<body>
</body>
</html>

实现声明式代码, 而非命令式。compose 表达式只是简单地指出了这样一个事实: 两个行为的组合。 这再次说明,声明式为潜在的代码更新提供了支持,使得我们的应用代码成为了一种高级规范(high level specification)。

./flickr.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require.config({
    paths: {
        ramda: 'https://cdnjs.cloudflare.com/ajax/libs/ramda/0.13.0/ramda.min',
        jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min'
    }

});

require([
        'ramda',
        'jquery'
    ],
    function(_, $) {
        var trace = _.curry(function(tag, x) {
            console.log(tag, x);
            return x;
        })

        var Impure = {
            getJSON: _.curry(function(callback, url) {
                $.getJSON(url, callback)
            }),

            setHtml: _.curry(function(sel, html) {
                $(sel).html(html)
            })

        };

        var img = function(url) {
            return $('<img />', { src: url })
        }

        //////////////////////////
        var url = function(term) {
            return 'https://api.flickr.com/services/feeds/photos_public.gne?tags=' + term + '&format=json&jsoncallback=?';
        }

        var app = _.compose(Impure.getJSON(trace("response")), url);
        var mediaUrl = _.compose(_.prop('m'), _.prop('media'));

        var srcs = _.compose(_.map(mediaUrl), _.prop('items'));

        // var renderImages = _.compose(Impure.setHtml(body), srcs);
        // var app = _.compose(Impure.getJSON(renderImages), url);

        var images = _.compose(_.map(img), srcs);
        var renderImages = _.compose(Impure.setHtml("body"), images);
        // var app = _.compose(Impure.getJSON(renderImages), url);

        app("cats");

        // var prop = _.curry(function(property, object) {
        //     return object[property]
        // })

    }
)
Licensed under CC BY-NC-SA 4.0