22 August 2014

While working with some results from an API call, I needed to copy several (but not all) of their properties onto model objects I would use for application state. Most copy or clone functions grab every property from the source object but I wanted to just list a few.

function copy( prop ) {
var receiver, target;
function bindFrom( obj ) {
target = obj;
return copyProp();
}
function bindTo( obj ) {
receiver = obj;
return copyProp();
}
function copyProp() {
if ( target && receiver ) {
if ( prop in target ) {
receiver[prop] = target[prop];
}
return receiver;
}
return {
from: bindFrom,
to: bindTo
};
}
return copyProp();
};
view raw copy.js hosted with ❤ by GitHub

I like code that tells a story. It’s hard for other developers (or future me) to get confused:

copy( 'some_property' ).from( objectA ).to( objectB );

When I use it to collect specific property values from API results, I map over a pre-determined list, like this:

var result = {id:1, foo: 'bar', baz: null};
var myObj = ['foo', 'baz']
.map( copy )
.reduce( function ( obj, copyProp ) {
return copyProp.from( result ).to( obj );
}, {} );
//=> {foo: "bar", baz: null}
view raw example.js hosted with ❤ by GitHub


Discussion: