Created
July 6, 2013 23:16
-
-
Save mohayonao/5941630 to your computer and use it in GitHub Desktop.
デフォルト引数をつける
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var isDictionary = function(obj) { | |
return obj && obj.constructor === Object; | |
}; | |
var args_resolution = function(keys, vals, given) { | |
var dict, args = vals.slice(); | |
if (isDictionary(given[given.length - 1])) { | |
dict = given.pop(); | |
for (var key in dict) { | |
var index = keys.indexOf(key); | |
if (index !== -1) { | |
args[index] = dict[key]; | |
} | |
} | |
} | |
for (var i = 0, imax = Math.min(given.length, args.length); i < imax; ++i) { | |
args[i] = given[i]; | |
} | |
if (dict) { | |
args.push(dict); | |
} | |
return args; | |
}; | |
var defaults_for = function(func) { | |
var body = "" + func; | |
var def = body.replace(/^\s*function\s*\(.+\)\s*{\s*(?:"use strict";)?\s*\/\/\s*{([^\n]+?)}[\S\s]+$/m, "$1"); | |
if (def !== body) { | |
var origin = func, keys = [], vals = []; | |
def = def.split(","); | |
for (var i = 0, imax = def.length; i < imax; ++i) { | |
var items = def[i].trim().split("="); | |
keys.push(items[0].trim()); | |
vals.push(items.length === 1 ? 0 : eval(items[1])); | |
}; | |
func = function() { | |
return origin.apply(this, args_resolution(keys, vals, Array.prototype.slice.call(arguments))); | |
}; | |
} | |
return func; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var madd = defaults_for(function(val, mul, add) { | |
// { val=0, mul=1, add=0 } | |
return val * mul + add; | |
}); | |
console.log(madd(10)); // 10 (= 10 * 1 + 0) | |
console.log(madd(10, 2)); // 20 (= 10 * 2 + 0) | |
console.log(madd(10, {add:20})); // 30 (= 10 * 1 + 20) | |
var Int = (function() { | |
function Int(n) { | |
this.value = n|0; | |
} | |
Int.prototype.madd = defaults_for(function(mul, add) { | |
// { mul=1, add=0 } | |
return (this.value * mul + add)|0; | |
}); | |
return Int; | |
})(); | |
var i = new Int(Math.PI); | |
console.log(i.madd(2)); // 6 (= 3 * 2 + 0) | |
console.log(i.madd({mul:3, add:-9})); // 0 (= 3 * 3 - 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment