Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/Buffer.mo
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,19 @@ module {
};
};

/// Construct a buffer from an array.
public func fromArray<T>(arr: [T]): Buffer<T> {
let count = arr.size();
let buffer = Buffer<T>(count);

var i = 0;
label l loop {
if (i >= count) break l;
buffer.add(arr[i]);
i += 1;
};

buffer
};
Comment on lines +149 to +162
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Why not simply

Suggested change
/// Construct a buffer from an array.
public func fromArray<T>(arr: [T]): Buffer<T> {
let count = arr.size();
let buffer = Buffer<T>(count);
var i = 0;
label l loop {
if (i >= count) break l;
buffer.add(arr[i]);
i += 1;
};
buffer
};
/// Construct a buffer from an array.
public func fromArray<T>(arr: [T]): Buffer<T> {
return { count = arr.size(); elems = Array.thaw(arr) }
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks definitely better!
But can it create an instance of the Buffer class? Motoko Playground shows error:
image

It was intended to be a static method like let buf = Buffer.fromArray<Nat>([1, 2, 3]);
Probably it will work as an instance method like:

let buf = Buffer.Buffer<Nat>(0);
buf.fromArray([1, 2, 3]);

image

Not sure we can leave the name fromArray in this case, because in other files in base lib from* methods are static.

Link to the playground https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/?tag=2337373062

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, right, Motoko classes have only one constructor usually…

Maybe first add buffer.addArray (which can be implemented efficiently using Array.thraw, especially if the buffer is empty before), and then the fromArray function.


}