#1186 new
Arnau Sanchez

add Enumerable#mash

Reported by Arnau Sanchez | December 17th, 2010 @ 09:21 PM

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.

Comments and changes to this ticket

  • Juriy Zaytsev

    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).

  • Arnau Sanchez

    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.

  • Arnau Sanchez

    Arnau Sanchez October 17th, 2011 @ 09:39 AM

    • Tag changed from hash enumerable functional, --enhacements to --enhacements, enumerable, functional, hash
  • Jason Westbrook

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

Pages