Skip to content

Instantly share code, notes, and snippets.

@snichme
Created November 5, 2014 21:04
Show Gist options
  • Save snichme/00e2bff037d8385e03e4 to your computer and use it in GitHub Desktop.
Save snichme/00e2bff037d8385e03e4 to your computer and use it in GitHub Desktop.
JS model with mixins
(function() {
'use strict';
/** Helper methods */
function merge(obj1, obj2) {
Object.keys(obj2).forEach(function(key) {
obj1[key] = obj2[key];
});
return obj1;
}
function mixinMethods(data, mixins) {
mixins = mixins || [];
return mixins.reduce(function(all, curr) {
return merge(all, curr(data));
}, {});
}
/* User model */
function user(data, mixins) {
function fullname() {
return (data.firstname || ' - ') + ' ' + data.surname;
}
return Object.freeze(merge(mixinMethods(data, mixins), {
fullname: fullname
}));
}
/* Length model */
function length(spec) {
function ll() {
var string = spec.firstname;
if(!string) {
return 0;
}
return string.length;
}
return Object.freeze({
length: ll
});
}
var user1 = user({
firstname: 'Magnus',
surname: 'Landerblom'
}, [length]);
console.log(user1.fullname(), user1.length());
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment