Skip to content

Instantly share code, notes, and snippets.

@ashwell
Last active April 2, 2018 19:44
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 ashwell/f2f863f323952ff10bebf4c7c405960d to your computer and use it in GitHub Desktop.
Save ashwell/f2f863f323952ff10bebf4c7c405960d to your computer and use it in GitHub Desktop.
class SimpleMath {
constructor( n ) {
this.n = n;
}
static given( n ) {
return new SimpleMath( n );
}
add( m ) {
this.n += m;
return this;
}
subtract( m ) {
this.n -= m;
return this;
}
multiply( m ) {
this.n *= m;
return this;
}
divide( m ) {
this.n /= m;
return this;
}
value() {
return this.n;
}
}
function given(n) {
return SimpleMath.given(n);
// or new SimpleMath(n);
}
const proto = {
multiply ( a ) {
this.n *= a;
return this;
},
add ( a ) {
this.n =+ a;
return this;
},
divide ( a ) {
this.n /= a;
return this;
},
subtract ( a ) {
this.n -= a;
return this;
},
value () {
return this.n;
}
};
function given(n) {
let instance = Object.create( proto );
instance.n = n;
return instance;
}
/**
* Note this version works a little differently. Where the other
* versions do each operation as they happen, this version
* waits until `value` is called before evaluating the entire expression.
* This means this version will find the correct "mathematical" answer (as a single equation).
**/
// map method names to related operator
const
methodToOperator = Object.freeze({
add: '+',
subtract: '-',
multiply: '*',
divide: '/'
});
// single get handler for known methods
const handlers = {
get( target, prop, receiver ) {
if ( methodToOperator.hasOwnProperty( prop )) {
const operator = methodToOperator[ prop ];
return function( m ) {
target.eq += ` ${ operator } ${ m }`; // builds an equation
target.n = eval( `${ target.n } ${ operator } ${ m }` ); // calculate as you go
return receiver;
}
}
if ( prop === 'value' ) {
return function() {
// console.log( `curr n: ${ target.n }\ncurr eq: ${ target.eq }` );
return eval( target.eq );
};
}
}
};
function given( n ) {
return new Proxy({ n, eq: `${ n }` }, handlers );
}
@forrest-rival
Copy link

would be cool to save the entire stringified equation and just do a single eval on .value() so you could log the current equation if you wanted (sort of like how you can log sql text with query builders like knex)

@ashwell
Copy link
Author

ashwell commented Apr 2, 2018

@forrest-rival pretty sure it does that already. The equation is saved as .eq on the original target object. Then when value is requested a function is returned that runs the eval over the target .eq equation string.

The n value is the "calculate as you go" version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment