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
Rewrite the function copy_attributes so that it makes a loop over
var keys = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh'];
Write a copy_attributes_factory function so that we can write
var copy_attributes = copy_attributes_factory(keys);
Write a Fields class such that something like this will work:
var aaa = Fields(keys); aaa.copy_attributes(src, tgt);
Hints¶
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
This applies even for function (aka method) calls.
Have the factory function store the keys in a closure.
There are many ways of writing Fields. Choose one that suits you.