JS函数式编程记录

2 minute read

JS函数式编程记录

第一部分 组合

组合

 1var compose = function(f, g) {
 2    return function(x) {
 3        return f(g(x));
 4    };
 5};
 6
 7var toUpperCase = function(x) { return x.toUpperCase(); };
 8var exclaim = function(x) { return x + '!'; };
 9var shout = compose(exclaim, toUpperCase);
10
11let result = shout("send in the clowns");

实例应用

./index.html

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

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

./flickr.js

 1require.config({
 2    paths: {
 3        ramda: 'https://cdnjs.cloudflare.com/ajax/libs/ramda/0.13.0/ramda.min',
 4        jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min'
 5    }
 6
 7});
 8
 9require([
10        'ramda',
11        'jquery'
12    ],
13    function(_, $) {
14        var trace = _.curry(function(tag, x) {
15            console.log(tag, x);
16            return x;
17        })
18
19        var Impure = {
20            getJSON: _.curry(function(callback, url) {
21                $.getJSON(url, callback)
22            }),
23
24            setHtml: _.curry(function(sel, html) {
25                $(sel).html(html)
26            })
27
28        };
29
30        var img = function(url) {
31            return $('<img />', { src: url })
32        }
33
34        //////////////////////////
35        var url = function(term) {
36            return 'https://api.flickr.com/services/feeds/photos_public.gne?tags=' + term + '&format=json&jsoncallback=?';
37        }
38
39        var app = _.compose(Impure.getJSON(trace("response")), url);
40        var mediaUrl = _.compose(_.prop('m'), _.prop('media'));
41
42        var srcs = _.compose(_.map(mediaUrl), _.prop('items'));
43
44        // var renderImages = _.compose(Impure.setHtml(body), srcs);
45        // var app = _.compose(Impure.getJSON(renderImages), url);
46
47        var images = _.compose(_.map(img), srcs);
48        var renderImages = _.compose(Impure.setHtml("body"), images);
49        // var app = _.compose(Impure.getJSON(renderImages), url);
50
51        app("cats");
52
53        // var prop = _.curry(function(property, object) {
54        //     return object[property]
55        // })
56
57    }
58)