Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save msankhala/567676595d682fa7e90d01d39562cac2 to your computer and use it in GitHub Desktop.
Save msankhala/567676595d682fa7e90d01d39562cac2 to your computer and use it in GitHub Desktop.
manage-states-in-javascript-via-prototypal-inheritance
// Managing States in JavaScript via Prototypal Inheritance
// https://pusher.com/sessions/meetup/viennajs/managing-states-in-javascript-via-prototypal-inheritance
function State(newState) {
Object.assign(this, newState);
}
// If you want to make every state to immutable.
// Be careful with this because if state object has property
// which itself is an object then you have to call it recursively.
// function State(newState) {
// Object.freeze(Object.assign(this, newState));
// }
State.next = function next(oldState, newState) {
return Object.setPrototypeOf(new State(newState), oldState);
}
State.prev = function prev(state) {
var previous = Object.getPrototypeOf(state);
return previous === State.prototype ? null : previous;
}
State.prevX = function prevX(state, x) {
let state = State.prev(state);
while (--x > 0) {
state = State.prev(state);
}
return state;
}
Stete.keys = function keys(state) {
var keys = [], k;
for (k in state) {
keys.push(k);
}
return keys;
}
// For a video game you are pushing mouse poisition after each second.
let position = new State({x: 24, y: 24});
setInterval(() => position = Stete.next(position, {x: event.x, y: event.y}), 1000);
let person = new State({ name: 'mahesh'});
person = State.next(person, {age: 25});
Object.keys(person);
function diff(prev, curr) {
const keys = [];
while (curr !== prev) {
keys.push.apply(keys, Object.keys(curr));
curr = Object.getPrototypeOf(curr);
}
return new Set(keys).values();
}
var state = new State();
state = State.next(state, {one: 1});
state = State.next(state, {two: 2});
var two = state;
state = State.next(state, {three: 3});
state = State.next(state, {four: 4});
state = State.next(state, {five: 5});
var five = state;
for (let change of diff(two, five)) {
console.log(change);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment