Last active
April 28, 2016 13:50
-
-
Save klaygomes/7940a4c3e29be6e7aff2cb63dfaadb7c to your computer and use it in GitHub Desktop.
Requisitos: Dado um Schema inicial simples, aplicar funções de transformação em campos definidos pelo usuário.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var Schema = { | |
name: { | |
type: String | |
}, | |
lastname: { | |
type: String | |
}, | |
avatar: { | |
type: Number | |
}, | |
birthday: { | |
type: Date | |
} | |
}; | |
/* código de intra-estrutura code */ | |
class Action { | |
constructor(propName, action){ | |
this.propName = propName; | |
this.do = action; | |
} | |
static for(propName, action){ | |
return new Action(propName, action); | |
} | |
} | |
class Mediator { | |
constructor(schema){ | |
var self = this; | |
self.itens = new Map(); | |
self.completedList = new Map(); | |
for(let prop in schema) | |
self.itens.set(prop, Action.for(prop, function(value) { | |
self.completedList.has(prop) && self.completedList.get(prop).call(value, value); | |
return value; | |
})); | |
} | |
onComplete(propName, callback){ | |
this.completedList.set(propName, callback) | |
} | |
apply(obj){ | |
for(let prop in obj){ | |
this.itens.has(prop) && this.itens.get(prop).do.call(obj, obj[prop]); | |
} | |
} | |
static for(schema, actions){ | |
var mediator = new Mediator(schema); | |
actions.reverse().forEach( (item) =>{ | |
let cb = mediator.itens.get(item.propName); | |
mediator.itens.set(item.propName, Action.for(item.propName, function(param){ | |
let holder = item.do.call(param, param); | |
return cb.do.call(holder, holder); | |
})); | |
}); | |
return mediator; | |
} | |
} | |
/* código do cliente */ | |
var actions = [ | |
Action.for('name', String.prototype.toUpperCase), | |
Action.for('name', str => str.substring(0,5)) | |
]; | |
var mediator = Mediator.for(Schema, actions); | |
mediator.onComplete('name', function(value){ | |
console.log(value); | |
}); | |
mediator.onComplete('birthday', function(value){ | |
console.log(value); | |
}); | |
mediator.apply({ | |
"name": "Cleiton", | |
"lastname":"Gomes", | |
"birthday": new Date(1986, 2, 13) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment