多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 示例 <details> <summary>index.html</summary> ``` <!DOCTYPE html> <html> <head> <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> ``` </details> <br/> <details> <summary>flickr.js</summary> ``` requirejs.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) { console.log(html); $(sel).html(html); }), }; var url = function (term) { return 'https://api.flickr.com/services/feeds/photos_public.gne?tags=' + term + '&format=json&jsoncallback=?'; }; var img = function (url) { return $('<img />', { src: url }); }; // debug // { // title:"xxx", // items:[ // { // title:"xxx", // media:{ // m:"http://...." // } // }, // ... // ] // } // var app = _.compose(Impure.getJSON(trace("response")), url); var mediaUrl = _.compose(_.prop('m'), _.prop('media')); var srcs = _.compose(_.map(img,mediaUrl),_.prop("items")); var readerImage = _.compose(Impure.setHtml("body"),_.map(img),srcs) var app = _.compose(Impure.getJSON(readerImage),url) app("cat") }); ``` </details> <br/> ## 有原则的重构 从 items 中获取 url map一次,从 url 转为 url 转为 img map 了一次,所以可以进行优化 根据map的结合律:`var law = compose(map(f), map(g)) == map(compose(f, g));` ``` // 原有代码 var mediaUrl = _.compose(_.prop('m'), _.prop('media')); var srcs = _.compose(_.map(mediaUrl), _.prop('items')); var images = _.compose(_.map(img), srcs); // 1.通过等式推导(equational reasoning)及纯函数的特性 var mediaUrl = _.compose(_.prop('m'), _.prop('media')); var images = _.compose(_.map(img), _.map(mediaUrl), _.prop('items')); // 2.运用结合律 var mediaUrl = _.compose(_.prop('m'), _.prop('media')); var images = _.compose(_.map(_.compose(img, mediaUrl)), _.prop('items')); // 3. 提取map的可读性 var mediaUrl = _.compose(_.prop('m'), _.prop('media')); var mediaToImg = _.compose(img, mediaUrl); var images = _.compose(_.map(mediaToImg), _.prop('items')); ```