Skip to content

Instantly share code, notes, and snippets.

@chul-hyun
Last active October 17, 2015 06:36
Show Gist options
  • Save chul-hyun/b6599318d80860164ba4 to your computer and use it in GitHub Desktop.
Save chul-hyun/b6599318d80860164ba4 to your computer and use it in GitHub Desktop.
milk and egg
var developer = objInit({
info: {
name : '개발자',
state : 'go home'
}
});
var wife = objInit({
info: {
name : '아내'
}
});
var market = objInit({
info: {
name : '마트'
},
items: {
egg : 100,
milk : 100
}
});
if(developer.info.state == 'go home'){
developer.purchase(market, 'milk', 2);
if(market.hasItem('egg')){
developer.purchase(market, 'milk', 6)
}
}
developer.state = 'stay home';
developer.allGive(wife, 'milk');
market.print();
developer.print();
wife.print();
//util
function simpleExtend(object, target){
for(key in object){
target[key] = object[key];
}
}
function objInit(obj){
var methods = {
print : print,
allGive : allGive,
give : give,
purchase : purchase,
removeItem : removeItem,
addItem : addItem,
hasItem : hasItem,
getNum : getNum,
setNum : setNum
}
simpleExtend(methods, obj);
obj.info = obj.info ? obj.info : {};
obj.info.name = obj.info.name ? obj.info.name : 'undefined';
obj.items = obj.items ? obj.items : {};
return obj;
}
// methods
function print(){
console.log('%s은(는)...', this.info.name);
var has = false;
for(item in this.items){
var num = getNum.call(this, item);
if(num > 0){
console.log('%s을(를) %i개', item, num);
has = true;
}
}
if(has){
console.log('갖고있습니다.');
}else{
console.log('아무것도 갖고있지 않습니다.');
}
}
function allGive(other){
console.log('%s은(는) 갖고있는 것을 %s에(에게) 모두 주는것을 시도.', this.info.name, other.info.name);
for(item in this.items){
var num = getNum.call(this, item);
give.call(this, other, item, num);
}
console.log('성공적');
}
function give(other, item, num){
console.log('%s은(는) %s %i개를 %s에(에게) 주는것을 시도.', this.info.name, item, num, other.info.name);
removeItem.call(this, item, num);
addItem.call(other, item, num);
console.log('성공적');
}
function purchase(other, item, num){
console.log('%s은(는) %s에서 %s %i개를 구매 시도.', this.info.name, other.info.name, item, num);
removeItem.call(other, item, num);
addItem.call(this, item, num);
console.log('성공적');
}
function addItem(item, num){
this.items[item] = this.items[item] ? this.items[item] + num : num;
}
function removeItem(item, num){
if(num <= 0){
return;
}
if(!hasItem.call(this, item)){
throw Error(this.info.name +'에게 '+item+'이(가) 없어서 제거 실패');
}
if(this.items[item] < num){
throw Error(this.info.name +'에게 '+item+'이(가) '+this.getNum(item)+'개 밖에 없어서 '+num+'개 제거 실패');
}
this.items[item] = this.getNum(item) - num;
}
function hasItem(item){
if(!this.items[item] || this.items[item] <= 0){
return false;
}
return true;
}
function getNum(item){
if(hasItem.call(this, item)){
return this.items[item];
}
return 0;
}
function setNum(item, num){
this.items[item] = num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment