Skip to content

Commit

Permalink
feat(stdlib): Add fromArray to Queue module (#1932)
Browse files Browse the repository at this point in the history
Co-authored-by: Blaine Bublitz <blaine.bublitz@gmail.com>
  • Loading branch information
spotandjake and phated authored Dec 31, 2023
1 parent 48de28b commit 1c35a94
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
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

0 comments on commit 1c35a94

Please sign in to comment.