Note that there are some explanatory texts on larger screens.

plurals
  1. POImplement map in javascript that supports object methods as mapped functions?
    primarykey
    data
    text
    <p>I recently tried to use an implementation of map in javascript to create a bunch of items, then apply them to an objects add method.</p> <p>Firstly with a bog standard implementation of map.</p> <pre><code>var map = function (fn, a) { for (i = 0; i &lt; a.length; i++) { a[i] = fn(a[i]); } } </code></pre> <p>Setup.</p> <pre><code>var translateMenu = new Menu; var languages = [ ['Chinese' , 'zh-CN'] , ['German' , 'de'] , ['French' , 'fr'] , ['Portugese' , 'pt'] , ['Hindi' , 'hi'] ]; </code></pre> <p>And my function... (not anonymous, as it's later used when adding the translateMenu to mainMenu.)</p> <pre><code>var langItem = function (language, subMenu) { return new MenuItem(language[0], 'http://translate.google.com/translate?u=www.example.com&amp;hl=en&amp;ie=UTF-8&amp;tl=en&amp;sl=' + language[1] , "" , subMenu); } map ( langItem , languages ); </code></pre> <p>This all worked fine, I now had an array of MenuItems to throw around.</p> <p>Trying to call <code>map( Menu.add , languages )</code> would result in internal variables of Menu being undefined, and the call failing.<br> Now I'm certain this has to do with the scope of the <code>Menu.add()</code> method, so i thought if I passed in the object as well, it might work. </p> <p>I tried creating a new map function that would accept objects and functions, but had the same undefined error.</p> <pre><code>objMap (fn , obj , a) { for (i = 0; i &lt; a.length; i++) { obj.fn(a); } } objMap ( add , translateMenu , languages ); // failed </code></pre> <p>I worked around this by extending Menu with addAll() to take an array, which works fine...</p> <pre><code>Menu.prototype.addAll = function (items){ for (i = 0; i &lt; items.length; i++) { this.add(items[i]); } } translateMenu.addAll( languages ); // yay! but I want a more elegant solution. </code></pre> <p>Anyway, my question is, <strong>how could I implement map (or a similar generic function) to actually support using object methods as my mapped functions?</strong>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload