Exercise two

Here’s some more JavaScript code I found. I’ve changed the names of everything to hide the origin of the code. But it’s not something I’ve made up.

var copy_attributes = function(tgt, src){

    tgt.aaa = src.get_aaa();
    tgt.bbb = src.get_bbb();
    tgt.ccc = src.get_ccc();
    tgt.ddd = src.get_ddd();
    tgt.eee = src.get_eee();
    tgt.fff = src.get_fff();
    tgt.ggg = src.get_ggg();
    tgt.hhh = src.get_hhh();
};

The exercise is

  1. Rewrite the function copy_attributes so that it makes a loop over

    var keys = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh'];
    
  2. Write a copy_attributes_factory function so that we can write

    var copy_attributes = copy_attributes_factory(keys);
    
  3. Write a Fields class such that something like this will work:

    var aaa = Fields(keys);
    aaa.copy_attributes(src, tgt);
    

Hints

  1. In JavaScript attribute access and item access are the same. First we use item access to set:

    js> a = {}
    [object Object]
    js> key = 'attrname'
    attrname
    js> a[key] = 42
    42
    

    and then we use attribute access to get:

    js> a.attrname
    42
    
  2. This applies even for function (aka method) calls.

  3. Have the factory function store the keys in a closure.

  4. There are many ways of writing Fields. Choose one that suits you.