Skip to content

Instantly share code, notes, and snippets.

@towerofnix
Created September 1, 2021 01:56
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 towerofnix/c445f785aeaec0507274a426cc443b4d to your computer and use it in GitHub Desktop.
Save towerofnix/c445f785aeaec0507274a426cc443b4d to your computer and use it in GitHub Desktop.
{
let order;
let memory;
let value;
let counter;
function reset() {
order = [];
memory = [];
value = [];
counter = 0;
}
reset();
Object.prototype.valueOf = function() {
if (!memory.includes(this)) {
memory.push(this);
value.push(nextValue());
}
const v = value[memory.indexOf(this)];
order.push(v);
return v;
};
function nextValue() {
return Math.random(); /* guaranteed sequential */
}
function search(result) {
function tree(acc, i) {
if (i >= order.length - 1) return acc;
const next = order[++i];
return {
'+': tree(acc + next, i),
'-': tree(acc - next, i),
'*': tree(acc * next, i),
'/': tree(acc / next, i)
}
}
function climb(branch) {
const entries = Object.entries(branch);
if (typeof entries[0][1] === 'number') {
const leaf = entries.find(x => x[1] === result)[0];
return leaf && [leaf];
} else {
for (const entry of entries) {
const path = climb(entry[1]);
if (path) return [entry[0], ...path];
}
}
}
return climb(tree(order[0], 0));
}
function V(result) {
try {
if (order.length === 0) {
return {values: [result], operators: []};
}
return {
values: order.map(n => memory[value.indexOf(n)]),
operators: search(result)
};
} finally {
reset();
}
}
function show(msg, {values, operators}) {
let expr = JSON.stringify(values[0]);
for (let i = 0; i < operators.length; i++) {
expr += ` ${operators[i]} `;
expr += JSON.stringify(values[i + 1]);
}
console.log(msg, expr);
}
a = {A: 'apple'};
b = {B: 'bison'};
show('a + a:', V(a + a));
show('b + b:', V(b + b));
show('a + b:', V(a + b));
show('b + a:', V(b + a));
console.log('---');
show('a * a:', V(a * a));
show('b * b:', V(b * b));
show('a * b:', V(a * b));
console.log('---');
show('a + a + b:', V(a + a + b));
show('b + a + b + a:', V(b + a + b + a));
console.log('---');
show('a:', V(a));
console.log('---');
show('a / b:', V(a / b));
show('a / a:', V(a / a));
show('a / a * b:', V(a / a * b));
show('b / b * a:', V(b / b * a)); // :)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment