Last active
January 14, 2017 07:21
-
-
Save saginadir/0df53a02dc75fa2db5b9ddd9a55e2c35 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Student { | |
constructor (student) { | |
this.student = student; | |
} | |
map(f) { | |
const student = Object.assign({}, this.student); | |
return new Student(f(student)) | |
} | |
take(item) { | |
const student = Object.assign({}, this.student); | |
student.items.push(item); | |
return new Student(student); | |
} | |
giveHomework(homeworkQuantity) { | |
const student = Object.assign({}, this.student); | |
student.homeworkQuantity += homeworkQuantity; | |
return new Student(student); | |
} | |
doHomework() { | |
const student = Object.assign({}, this.student); | |
const doneHomework = student.items.reduce((done, item) => { | |
if(item === 'pencil') { | |
student.homeworkQuantity -= 1; | |
return true; | |
} | |
return doneHomework; | |
}, false); | |
if(!doneHomework) { | |
console.log('Missing pencil to do homework'); | |
} | |
return new Student(student); | |
} | |
logMyState() { | |
console.log(this.student); | |
return new Student(this.student); | |
} | |
static newStudent(name) { | |
return new Student({ | |
name, | |
items: [], | |
homeworkQuantity: 0, | |
}); | |
} | |
} | |
const student = Student.newStudent('Josh'); | |
student | |
.logMyState() | |
.giveHomework(2) | |
.doHomework() // "Missing pencil to do homework" | |
.take('ruler') | |
.take('coffee') | |
.logMyState() | |
.doHomework() // "Missing pencil to do homework" | |
.take('pencil') | |
.doHomework() | |
.doHomework() | |
.logMyState() | |
.map(student => Object.assign({}, student, { homeworkQuantity: 'rebel' })) | |
.logMyState(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment