Skip to content

Instantly share code, notes, and snippets.

@okunishinishi
Created July 25, 2015 08:49
Show Gist options
  • Save okunishinishi/273f9a48f153712c4b07 to your computer and use it in GitHub Desktop.
Save okunishinishi/273f9a48f153712c4b07 to your computer and use it in GitHub Desktop.
JavaScriptの関数で、可変長・任意の引数をいい感じに処理する ref: http://qiita.com/okunishinishi@github/items/d6f3cffa58ef480c4af7
doSomething('foo')
doSomething('foo','bar')
doSomething('foo','bar', 'baz');
doSomething('foo','bar', {verbose:true});
doSomething('foo','bar', function done(){/*...*/})
doSomething('foo','bar', {verbose:true}, function done(){/*...*/})
function doSomething(val, options, callback){
var lastArg = arguments[arguments.length - 1];
if (typeof(lastArg) !== 'function') {
options = lastArg;
callback = null;
/*...*/
}
}
function doSomething(val, options, callback){
var args = Array.prototype.slice.call(arguments, 0);
var lastArg = args.pop();
if (typeof(lastArg) === 'function' ) {
}
}
var argx = require('argx'); // 引数解釈用のモジュール
function doSomething(values, options, callback) {
var args = argx(arguments);
callback = args.pop('function'); // 末尾が関数の場合のみ取得
options = args.pop('object'); // 残りの末尾がオブジェクトの場合のみ取得
values = args.remain(); // 残りをまとめて取得
/*...*/
}
/** 引数解釈クラス */
function Argx(args) {
this.values = Array.prototype.slice.call(args, 0);
}
Argx.prototype = {
values: undefined,
_slice: function (index, type) {
var s = this;
var hit = (!type) || (typeof(s.values[index]) === type);
if (hit) {
return s.values.splice(index, 1).shift();
} else {
return undefined;
}
},
/** 先頭の型が一致した場合のみ取得 */
shift: function (type) {
var s = this;
return s._slice(0, type);
},
/** 末尾の型が一致した場合のみ取得 */
pop: function (type) {
var s = this;
return s._slice(s.values.length - 1, type);
},
/** 残り全部取得 */
remain: function () {
var s = this;
var values = s.values;
s.values = undefined;
return values;
}
};
/** 引数解釈関数 */
function argx(args) {
return new Argx(args);
}
function doSomething(values, options, callback) {
var args = argx(arguments); //Argxクラスのインスタンス生成
callback = args.pop('function');
options = args.pop('object');
values = args.remain();
console.log({
callback: callback,
options: options,
values: values
}); // -> { callback: [Function: done], options: { verbose: true }, values: [ 'v1', 'v2' ] };
}
doSomething("v1", "v2", {verbose: true}, function done() {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment