here is my js code that I would like to convert to AssemblyScript
function make_func_array(size){
function f1(w){
w.val+=1
}
function f2(w){
w.val+=10
}
var ans=[]
for (let i=0;i<size;i++){
ans.push(f1)
ans.push(f2)
}
return ans
}
function run_ar(ar,val){
var w={val}
for(let f of ar){
f(w)
}
return w.val
}
var ar=make_func_array(10)
var ans=run_ar(ar,3)
console.log('ans',ans)
it uses an array of functions to execute some rudimentary calculation
my question is: does AssemblyScript supports array of functions? how would it write it in AssemblyScript?
yes, that's possible. Just need fill types
declare function log(i: i32): void;
class W {
val: i32;
}
function makeFnArr(size: i32): Array<(w: W) => void> {
const f1 = (w: W): void => {
w.val += 1;
}
const f2 = (w: W): void => {
w.val += 10;
}
let ans: Array<(w: W) => void> = [];
for (let i = 0; i < size; i++) {
ans.push(f1);
ans.push(f2);
}
return ans;
}
function runArr(arr: Array<(w: W) => void>, val: i32): i32 {
let w: W = { val };
for (let i = 0, len = arr.length; i < len; i++) {
let fn = arr[i];
fn(w);
}
return w.val;
}
var arr = makeFnArr(10);
var ans = runArr(arr, 3);
log(ans);