prototypejs / prototype

Prototype JavaScript framework
http://prototypejs.org/
Other
3.54k stars 640 forks source link

add Enumerable#mash #172

Closed jwestbrook closed 10 years ago

jwestbrook commented 10 years ago

previous lighthouse ticket #1186 by Arnau Sanchez


Programmers who have used Ruby's Facets know how useful Enumerable#mash is:

>> require 'facets'
>> ["Exit", "the", "dragon"].mash { |s| [s, s.length] }
=> {"Exit"=>4, "the"=>3, "dragon"=>6}

My proposal is to add this method to Prototype. I have no deep knowledge of the library internals, but this may be a possible implementation:

Enumerable.mash = function(iterator, context) {
  hash = $H();
  this.each(function(value, index) {
    var pair = iterator ? iterator.call(context, value, index) : value;
    hash.set(pair[0], pair[1]);
  });    
  return hash;
}
Object.extend(Array.prototype, Enumerable);

And now you can write:

> ["Exit", "the", "dragon"].mash(function(s) { return [s, s.length] }).inspect()
"#<Hash:{'Exit': 4, 'the': 3, 'dragon': 6}>"

I'll understand if the answer is 'no, we prefer not to bloat the library', but I think Enumerable#mash would encourage sound programming practices (compare it with the -IMHO- hideous imperative pattern 'init empty + iterate each + modify inplace + return') in the same way Enumerable#map does

jwestbrook commented 10 years ago

Juriy Zaytsev December 18th, 2010 @ 12:16 AM

Importance changed from “” to “Low” Very interesting method; looks useful indeed. I do think that mash would be an overkill here, considering that ES5 allows to achieve this same task rather elegantly. And simple.

['exit', 'the', 'dragon'].reduce(function(obj, key) {
  obj[key] = key.length;
  return obj; 
}, { });

See Array.prototype.reduce (on MDN or in ES5 spec).

jwestbrook commented 10 years ago

Arnau Sanchez December 18th, 2010 @ 12:36 AM

Oops, my bad, I keep forgetting about foldl/reduce/inject while writing JS, which is obviously the right approach to implement mash (and that's how it's also implemented in Ruby). Well, compact as it with reduce, the point was more about encouraging good practices, I think that having standard methods for the two-way Array<->Hash conversions is important. Thanks for taking it into consideration, though.