javascript function as an array -
// compute factorials , cache results properties of function itself. function factorial(n) { if (isfinite(n) && n>0 && n==math.round(n)) { // finite, positive ints if (!(n in factorial)) // if no cached result factorial[n] = n * factorial(n-1); // compute , cache return factorial[n]; // return cached result } else return nan; // if input bad } factorial[1] = 1; // initialize cache hold base case.
this code book javascript: definitive guide, 6th edition
i have following questions:
1)in below line how function being used array?
factorial[n] = n * factorial(n-1); // compute , cache
2)how can use in
operator function argument in below line?
if (!(n in factorial)) // if no cached
edit:
i got factorial[1] = 1;
sets property '1':1
in function factorial.
but possible set property of function below?
function f() { a: 2 } alert(f.a); //get 2 output
a function still object, can assign properties object. set 'n' property of factorial, don't have recalc every time. 'in' operator functioning flows this, being (but not completely) equivalent factorial.hasownproperty(n) in example. technically you're using factorial function map numbers keys, looks similar array.
Comments
Post a Comment