DEV Community

Cover image for SAM pattern, the origin of Meiosis
artydev
artydev

Posted on • Edited on

SAM pattern, the origin of Meiosis

The author of this famous pattern is Jean-Jacques Dubray. He wrote an introduction here SAM

You can see it in action here : SAMdemo

let actions = {
  countBy(step) {
    step = step || 1
    model.accept({incrementBy:step})
  }
}

let model = {
  counter: 1,
  accept(proposal) {
    this.counter += (proposal.incrementBy > 0) ? proposal.incrementBy : 0
    state.render(this)
  }
}

let state = {
  render(model) {
    if (!this.nextAction(model)) {
      console.log(model.counter)
    }
  }, 

  nextAction(model) {
    if (model.counter % 2 == 0) {
      actions.countBy(1)
      return true
    } else {
      return false
    }
  }
}

actions.countBy(2) 
Enter fullscreen mode Exit fullscreen mode

Rewrite with AI:

// --- State (immutable) ---
let model = {
  counter: 1
};

// --- Renderer ---
function render(model) {
  console.log(model.counter);
}

// --- Actions (pure) ---
function countBy(model, step = 1) {
  if (step <= 0) return model; // ignore invalid steps
  return { ...model, counter: model.counter + step };
}

// --- Next Action Logic ---
function nextAction(model) {
  // If counter is even, increment by 1
  if (model.counter % 2 === 0) {
    return countBy(model, 1);
  }
  return model; // no change
}

// --- Reactive Runner ---
function runAction(model, step) {
  // Apply initial action
  let newModel = countBy(model, step);

  // Keep applying nextAction until stable
  while (true) {
    const updatedModel = nextAction(newModel);
    if (updatedModel.counter === newModel.counter) break; // stable
    newModel = updatedModel;
  }

  render(newModel);
  return newModel;
}

// --- Usage ---
model = runAction(model, 2); // Starts the flow
Enter fullscreen mode Exit fullscreen mode

Top comments (0)