johnny-dreamguns
10/7/2019 - 9:37 AM

Flyweight

// FLYWEIGHT

const task = function(data) {
  this.name = data.name;
  this.flyweight = FlyweightFactory.get(data.project, data.priority, data.user, data.completed);
}
task.prototype.getProject = function() {
  return this.flyweight.project;
}
task.prototype.getPriority = function() {
  return this.flyweight.priority;
}
task.prototype.getUser = function() {
  return this.flyweight.user;
}
task.prototype.getCompleted = function() {
  return this.flyweight.completed;
}

function Flyweight(project, priority, user, completed) {
  this.project = project;
  this.priority = priority;
  this.user = user;
  this.completed = completed;
}

const FlyweightFactory = function () {
  const flyweights = {};

  const get = function (project, priority, user, completed){
    if(!flyweights[project + priority + user + completed]){
      flyweights[project + priority + user + completed] = 
        new Flyweight(project, priority, user, completed);
    }
    return flyweights[project + priority + user + completed];
  }

  return {
    get
  }
}()

const t1 = new task({
  name: 'test',
  project: 'Project 1',
  priority: 1,
  user: 'Johnny DG',
  completed: true
});

console.log(t1);