V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
undozen
V2EX  ›  JavaScript

转一个在知乎提的问题过来,关于 ES6 函数式编程

  •  
  •   undozen · 2014-03-19 00:00:04 +08:00 · 4220 次点击
    这是一个创建于 3692 天前的主题,其中的信息可能已经有所发展或是发生改变。
    http://www.zhihu.com/question/23083663
    确实,几乎没人回答,邀请了也没人。发过来大家看看。

    在 co 里面 yield 出来的值,如果有两个或以上参数,会变成数组,源码里面是这样的:

    function next(err, res) {
    var ret;

    // multiple args
    if (arguments.length > 2) res = slice.call(arguments, 1);

    先发出试格式再编辑。。。
    哎,也是缩进没有了。。
    知乎的图可以吗
    http://p2.zhimg.com/55/33/55338b98140299e709dd485f832a5631_m.jpg

    不行算了,看着累的大家还是移步知乎吧。
    继续

    比如:
    var asyncMath = function (list, cb) {
    setTimeout(function () {
    cb(null, Math.max.apply(Math, list), Math.min.apply(Math, list));
    }, 500);
    };

    co(function *() {
    console.log(yield tam([1,2,3,4,5]));

    这样出来的就是 [5, 1]

    但是有时候我只想要第一个参数,又懒得到处都
    var tmpArr = yield tam(...)
    var result = tmpArr[0];
    而是能直接 var result = yield sth(tam)(...)

    我不能直接用 binary 这样的函数:
    function binary(fn) {
    return function (a, b) {
    return fn.call(this, a, b);
    }
    }
    因为 tam([1,2,3])(fn) 收到的这个 fn 是 co 给进去的,我不应该改 co 的代码。

    我最后的代码是这个样子
    https://gist.github.com/undoZen/9615885

    达到了预想的效果。

    这样没问题了,但自己不敢肯定,这种做法常见吗?会不会某个库里面就有这样的函数呢?来这里求问大神们。

    当然,我知道如果有 destructuring assignment 就不必纠结了,但是目前 v8 还不支持啊。
    4 条回复    1970-01-01 08:00:00 +08:00
    undozen
        1
    undozen  
    OP
       2014-03-19 00:09:10 +08:00
    lepture
        2
    lepture  
       2014-03-19 00:42:53 +08:00
    StackOverflow & SegmentFault 是更合适的提问的地方。
    xieren58
        3
    xieren58  
       2014-03-19 10:03:43 +08:00   ❤️ 1
    直接 var aa = (yield asyncMath.bind(null, [1, 2, 3]))[0]; 不就完了??
    undozen
        4
    undozen  
    OP
       2014-03-19 10:28:19 +08:00
    @xieren58 对哦!!!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1103 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:13 · PVG 07:13 · LAX 16:13 · JFK 19:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.