Converting Ruby's yield inside of nested functions into Node.js

夙愿已清 提交于 2020-06-29 05:47:23

问题


I'm trying to convert a chunk of Ruby code into Node.js. One particular piece has me stumped, concerning yield. The code goes like this:

each_pair(hash["args"][0]) do |key, value, pair|
   # perform operations
end

...


def each_pair(hash)
    hash["props"].each do |p|
        yield(p["key"], p["value"], p)
    end
end

If I am reading this code correctly, it's saying "Iterate over the hash properties. For every element, call back out to the outer function and perform the operation with the given p["key"], p["value"], p values."

I can't really comprehend how this would look in Javascript. I'm acquainted with writing more trivial closures. Is a conversion possible at all? I'm guessing it's something like:

each_pair(hash["args"][0], function(key, value, pair) {
 // perform operations
}

...

function each_pair(hash, func) {
   hash["props"].forEach(p) {
       func(p["key"], p["value"], p)
   }
}

But something doesn't feel right...


回答1:


No, that's an OK translation. It's a little deceptive because any method in ruby can be called with an implicit block. If it's there, you can yield it. It's one of those shorthand tricks that you forget if you don't use them for a while :)

In the ruby version, you could also add a &block argument and replace yield(... with block.call(.... It'd be functionally equivalent.



来源:https://stackoverflow.com/questions/12490812/converting-rubys-yield-inside-of-nested-functions-into-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!