Trouble understanding Javascript nested function/closure -
i'm attempting port following javascript code ruby: https://github.com/iguigova/snippets_js/blob/master/pokerin4hours/pokerin4hours.js
i think have of sorted, function giving me grief is:
var kickers = function(idx){ // http://en.wikipedia.org/wiki/kicker_(poker) idx = idx || -15; var notplayed = math.max(input.length - 1/*player input*/ - 5, 0); return function(all, cardinality, rank) { return (all || 0) + (((cardinality == 1) && (notplayed-- <= 0)) ? rank * math.pow(10, ++idx) : 0); }; }();
and called further down so:
k = kickers(k, cardsofrank[i], i);
i wondering if explain how works in javascript. fact inner function has 3 parameters , outer has 1 confusing, given called 3 parameters. understand it's trying accomplish, can port code confidence.
var kickers = function(idx){ var xyz;//below function in return statement can access , argument idx return function(...) {//this ensures kickers infact function }; }();//invoke function instantly due () , assign output kickers
when javascript interpreter read above assignment kickers
execute anonymous function since function returns function, kickers
function (with closure). meaning kickers function have reference environment variables (idx , notplayed )
edit:
1) getting value of idx - since nothing passed while invoking function(last line ();
) idx undefined , idx = idx || -15;
assign value -15 it.
2) re-written without inner function? - yes. current implementation has advantage scope of idx
, notplayed
limited kicker function , not accessible globally. here how can write directly function
/* idx , notplayed global- meant used kicker * cant move inside function definition behave local variable function * , hence freed once executed , cannot maintain state of idx , notplayed */ var idx = -15; var notplayed = math.max(input.length - 1/*player input*/ - 5, 0); var kickers = function(all, cardinality, rank) { return(all || 0) + (((cardinality == 1) && (notplayed-- <= 0)) ? rank * math.pow(10, ++idx) : 0); }
Comments
Post a Comment