Skip to content

Commit 1c35a94

Browse files
spotandjakephated
andauthored
feat(stdlib): Add fromArray to Queue module (#1932)
Co-authored-by: Blaine Bublitz <blaine.bublitz@gmail.com>
1 parent 48de28b commit 1c35a94

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

compiler/test/stdlib/queue.test.gr

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,15 @@ let queue4 = Queue.copy(queue3)
126126
Queue.pop(queue4)
127127
assert Queue.toArray(queue4) == [> 2, 3]
128128

129+
// Queue.fromArray
130+
let qa1 = Queue.makeSized(8)
131+
Queue.push(1, qa1)
132+
Queue.push(2, qa1)
133+
Queue.push(3, qa1)
134+
Queue.push(4, qa1)
135+
assert Queue.fromArray([> 1, 2, 3, 4]) == qa1
136+
assert Queue.fromArray([>]) == Queue.makeSized(16)
137+
129138
module Immutable {
130139
from Queue use { module Immutable as Queue }
131140

stdlib/queue.gr

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,30 @@ provide let toArray = queue => {
201201
}, arr)
202202
}
203203

204+
/**
205+
* Creates a queue from an array.
206+
*
207+
* @param arr: The array to convert
208+
* @returns A queue containing all values from the array
209+
*
210+
* @since v0.6.0
211+
*/
212+
provide let fromArray = arr => {
213+
let size = Array.length(arr)
214+
let contents = if (size == 0) {
215+
Array.make(16, None)
216+
} else {
217+
Array.init(size * 2, i => {
218+
if (i < size) {
219+
Some(arr[i])
220+
} else {
221+
None
222+
}
223+
})
224+
}
225+
{ size, array: contents, headIndex: 0, tailIndex: size }
226+
}
227+
204228
/**
205229
* An immutable queue implementation.
206230
*/

stdlib/queue.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,31 @@ Returns:
269269
|----|-----------|
270270
|`Array<a>`|An array containing all values from the given queue|
271271

272+
### Queue.**fromArray**
273+
274+
<details disabled>
275+
<summary tabindex="-1">Added in <code>next</code></summary>
276+
No other changes yet.
277+
</details>
278+
279+
```grain
280+
fromArray : (arr: Array<a>) => Queue<a>
281+
```
282+
283+
Creates a queue from an array.
284+
285+
Parameters:
286+
287+
|param|type|description|
288+
|-----|----|-----------|
289+
|`arr`|`Array<a>`|The array to convert|
290+
291+
Returns:
292+
293+
|type|description|
294+
|----|-----------|
295+
|`Queue<a>`|A queue containing all values from the array|
296+
272297
## Queue.Immutable
273298

274299
An immutable queue implementation.

0 commit comments

Comments
 (0)