Skip to content

Instantly share code, notes, and snippets.

@williardx
Created December 26, 2019 04:29
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 williardx/9c531c878a6934b0255a4950553e9d64 to your computer and use it in GitHub Desktop.
Save williardx/9c531c878a6934b0255a4950553e9d64 to your computer and use it in GitHub Desktop.
Imperative and OOP vs. functional programming code example
// OOP anad imperative example
class Todo {
constructor(action, assignee) {
this.action = action
this.assignee = assignee
this.complete = false
}
toggleComplete() {
this.complete = !this.complete
}
}
class TodoList {
constructor(...todos) {
this.todos = [...todos]
}
assignAllTo(assignee) {
for (let i = 0; i < this.todos.length; i++) {
this.todos[i].assignee = assignee
}
}
completeAll() {
for (let i = 0; i < this.todos.length; i++) {
this.todos[i].toggleComplete()
}
}
}
// Make a few new todo items
let firstTodo = new Todo("hypnotize some people", "Will")
let secondTodo = new Todo("get bored", "Will")
// Create the list and reassign
let willsList = new TodoList(firstTodo, secondTodo)
// willsList.todos = [Todo("hypnotize some people", "Will", false), Todo("get bored", "Will", false)]
list.assignAllTo("Dad")
list.completeAll()
// willsList.todos = [Todo("hypnotize some people", "Dad", true), Todo("get bored", "Dad", true)]
// ------------------------------------------------------------------------------
// Functional example
function assignAllTo(todos, assignee) {
return todos.map((todo) => {
return {assignee: assignee, ...todo}
})
}
function completeAll(todos) {
return todos.map((todo) => {
return {complete: true, ...todo}
})
}
const firstTodo = {action: "hypnotize some people", assignee: "Will", complete: false}
const secondTodo = {action: "get bored", assignee: "Will", complete: false}
const willsList = [firstTodo, secondTodo]
const dadsList = completeAll(assignAllTo(willsList, "Dad"))
// dadsList = [{action: "hypnotize some people", assignee: "Dad", complete: true}, {action: "get bored", assignee: "Dad", complete: true}]
// willsList = [{action: "hypnotize some people", assignee: "Will", complete: false}, {action: "get bored", assignee: "Will", complete: false}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment