Skip to content

Instantly share code, notes, and snippets.

@mrtnbroder
Forked from DrBoolean/fp_arch.js
Created April 4, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtnbroder/dffc52ae2f5b68d91ffb8575afc9791e to your computer and use it in GitHub Desktop.
Save mrtnbroder/dffc52ae2f5b68d91ffb8575afc9791e to your computer and use it in GitHub Desktop.
OO => FP architecture refactor
// Simple example, but the idea holds for more complex objects.
/* 1) Start with OO */
// user.js
class User {
constructor(firstName, lastName, email) {
this.firstName = firstName
this.lastName = lastName
this.email = email
}
fullName() {
return [this.firstName, this.lastName].join(' ')
}
serialize() {
return {firstName: this.firstName, lastName: this.lastName, email: this.email}
}
spam() {
Emailer.reminderTpl(this.serialize).send()
}
}
export default User
/* 2) Next we make constructors into factories, methods into fns, and separate actions from calcs */
// user.js
const User = (firstName, lastName, email) => ({firstName, lastName, email})
const fullname = (firstName, lastName) => [firstName, lastName].join(' ')
const spamTemplate = user => Emailer.reminderTpl(user)
const sendSpam = tpl => tpl.send()
/* 3) Generalize names, reorganize */
// format.js
const joinWithSpace = (x, y) => [x, y].join(' ')
module.exports = {joinWithSpace}
// User was literally just the json we got from the server or db
// Spam did nothing other than delegate to Emailer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment