Skip to content

Instantly share code, notes, and snippets.

@sawapi
Last active December 23, 2022 22:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawapi/40445b4a5613ac613aa4 to your computer and use it in GitHub Desktop.
Save sawapi/40445b4a5613ac613aa4 to your computer and use it in GitHub Desktop.
calc.js

使い方

こんな感じ

// 10 + 20
calc( 10 ).plus( 20 ).get();
// > 30

// ( 9 - 7 ) * 5
calc( 9 ).minus( 7 ).multiply( 5 ).get();
// > 10

// 3 * ( 1 + 3 ) / 6
// 括弧内の計算はcalcでおこないそのオブジェクト自体を引数に指定する
calc( 3 ).multiply( calc( 1 ).plus( 3 ) ).divide( 6 ).get(); 
// > 2

http://sawapi.hatenablog.com/entry/2014/12/05/004710

!function( window ) {
// 簡易電卓クラス
// 3 * ( 1 + 3 ) / 6
// みたいな式を
// calc( 3 ).multiply( calc( 1 ).plus( 3 ) ).divide( 6 ).get();
// こんな感じで使えるように
var calc = function( num ) {
// calcクラスであればそのまま返す
if ( num instanceof calc ) {
return num;
}
// 数字以外は0にする
if ( typeof num !== 'number' ) {
num = 0;
}
// インスタンス生成
return new calc.prototype.init( num );
}
calc.prototype = {
// コンストラクタ
init: function( num ) {
this._num = num;
},
// たす
plus: function( num ) {
this._num += calc( num ).get();
return this;
},
// ひく
minus: function( num ) {
this._num -= calc( num ).get();
return this;
},
// かける
multiply: function( num ) {
this._num *= calc( num ).get();
return this;
},
// わる( 0でわることを考慮してない )
divide: function( num ) {
this._num /= calc( num ).get();
return this;
},
// 取得
get: function() {
return this._num;
}
}
// initのprototypeにcalcのprototypeをつっこむ
calc.prototype.init.prototype = calc.prototype;
window.calc = calc;
}( window );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment