I try to convert an array, a buffer, to a variant tree. In JavaScript I would .reduce()
it but I cannot wrap my head around how I should solve that in Motoko.
Anyone has maybe an example to share that show how to reduce a Buffer?
// The types
module {
public type Hash = Blob;
public type Key = Blob;
public type Value = Blob;
public type HashTree = {
#empty;
#pruned : Hash;
#fork : (HashTree, HashTree);
#labeled : (Key, HashTree);
#leaf : Value;
};
};
// What I am trying to do
public query func say() : async HashTree {
let tmp = Buffer.Buffer<(HashKey, HashTree)>(1);
tmp.add((Text.encodeUtf8("a"), #empty));
tmp.add((Text.encodeUtf8("b"), #empty));
let labeled = Buffer.Buffer<HashTree>(1);
for (val in tmp.vals()) {
labeled.add(#labeled val);
};
// What I try to achieve dynamically
let goal = #labeled(
"http_assets",
#fork(
#fork(
#labeled ("/a",
#leaf (Text.encodeUtf8("a"))
),
#labeled ("/b",
#leaf (Text.encodeUtf8("b"))
)
),
#fork(
#labeled ("/c",
#leaf (Text.encodeUtf8("c"))
),
#empty
)
)
);
return #labeled(
"http_assets",
labeled.vals(), // <-- here I get lost!??!
);
};
Motoko playground: Motoko Playground - DFINITY