Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(stdlib): Add fromArray to Queue module #1932

Merged
merged 4 commits into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions compiler/test/stdlib/queue.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ let queue4 = Queue.copy(queue3)
Queue.pop(queue4)
assert Queue.toArray(queue4) == [> 2, 3]

// Queue.fromArray
let qa1 = Queue.makeSized(8)
Queue.push(1, qa1)
Queue.push(2, qa1)
Queue.push(3, qa1)
Queue.push(4, qa1)
assert Queue.fromArray([> 1, 2, 3, 4]) == qa1
assert Queue.fromArray([>]) == Queue.makeSized(16)

module Immutable {
from Queue use { module Immutable as Queue }

Expand Down
24 changes: 24 additions & 0 deletions stdlib/queue.gr
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,30 @@ provide let toArray = queue => {
}, arr)
}

/**
* Creates a queue from an array.
*
* @param arr: The array to convert
* @returns A queue containing all values from the array
*
* @since v0.6.0
*/
provide let fromArray = arr => {
let size = Array.length(arr)
let contents = if (size == 0) {
Array.make(16, None)
} else {
Array.init(size * 2, i => {
if (i < size) {
Some(arr[i])
} else {
None
}
})
}
{ size, array: contents, headIndex: 0, tailIndex: size }
}

/**
* An immutable queue implementation.
*/
Expand Down
25 changes: 25 additions & 0 deletions stdlib/queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,31 @@ Returns:
|----|-----------|
|`Array<a>`|An array containing all values from the given queue|

### Queue.**fromArray**

<details disabled>
<summary tabindex="-1">Added in <code>next</code></summary>
No other changes yet.
</details>

```grain
fromArray : (arr: Array<a>) => Queue<a>
```

Creates a queue from an array.

Parameters:

|param|type|description|
|-----|----|-----------|
|`arr`|`Array<a>`|The array to convert|

Returns:

|type|description|
|----|-----------|
|`Queue<a>`|A queue containing all values from the array|

## Queue.Immutable

An immutable queue implementation.
Expand Down
Loading