简体   繁体   中英

Iterating over an array in a function

For my Google Docs spreadsheet module , I'd like a function to be able to accept an array of values and iterate over them, adding them to a hash. The spreadsheet submission form wants values in a format like this:

{"entry.0.single": value0,
 "entry.1.single": value1,
 "entry.2.single": value2}

If the function accepts an array like the following,

[value0, value1, value2]

is it possible to loop over them, keep a running counter, and create a hash? This would be a simple task in other languages. Python suffices for illustration:

hash = dict()
i = 0
for val in values:
  hash["entry.%s.single" % i] = val
  i += 1

Can that be done in KRL?

Recursive functions are your friend:

    a = ['value0', 'value1', 'value2'];

    r = function(a, h, n){
      top = a.head();
      newhash = h.put({'entry.#{n}.single':top});
      a.length() > 1 => r(a.tail(), newhash, n+1) | newhash;
    };

    out = r(a, {}, 0);

out has the value of {'entry.1.single' :'value1','entry.0.single' :'value0','entry.2.single' :'value2'};

A recursive function is needed here because you are doing a structure conversion. If you wanted an array back, you could have used the map() method .

Also, watch your base case writing recursive functions. KNS does enforce a recursion limit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM