diff options
-rw-r--r-- | changelog.md | 3 | ||||
-rw-r--r-- | lib/pure/collections/deques.nim | 23 |
2 files changed, 21 insertions, 5 deletions
diff --git a/changelog.md b/changelog.md index 281995b0e..f6f1f94cd 100644 --- a/changelog.md +++ b/changelog.md @@ -145,6 +145,9 @@ - Export `asyncdispatch.PDispatcher.handles` so that an external library can register them. +- Added `deques.toDeque`, which creates a deque from an openArray. The usage is + similar to procs such as `sets.toHashSet` and `tables.toTable`. Previously, + it was necessary to create an empty deque and add items manually. ## Language changes - The `=destroy` hook no longer has to reset its target, as the compiler now automatically inserts diff --git a/lib/pure/collections/deques.nim b/lib/pure/collections/deques.nim index 43ca536b6..54756707d 100644 --- a/lib/pure/collections/deques.nim +++ b/lib/pure/collections/deques.nim @@ -82,13 +82,25 @@ proc initDeque*[T](initialSize: int = 4): Deque[T] = ## Optionally, the initial capacity can be reserved via `initialSize` ## as a performance optimization. ## The length of a newly created deque will still be 0. + ## + ## See also: + ## * `toDeque proc <#toDeque,openArray[T]>`_ result.initImpl(initialSize) -proc initDeque*[T](arr: openArray[T]): Deque[T] = - ## Create a new deque initialized with an open array - result.initImpl(nextPowerOfTwo(arr.len)) - for i in 0 ..< arr.len: - result.addLast(arr[i]) +proc toDeque*[T](x: openArray[T]): Deque[T] {.since: (1, 3).} = + ## Creates a new deque that contains the elements of `x` (in the same order). + ## + ## See also: + ## * `initDeque proc <#initDeque,int>`_ + runnableExamples: + var a = toDeque([7, 8, 9]) + assert len(a) == 3 + assert a.popFirst == 7 + assert len(a) == 2 + + result.initImpl(x.len) + for item in items(x): + result.addLast(item) proc len*[T](deq: Deque[T]): int {.inline.} = ## Return the number of elements of `deq`. @@ -534,6 +546,7 @@ when isMainModule: assert first == 123 assert second == 9 assert($deq == "[4, 56, 6, 789]") + assert deq == [4, 56, 6, 789].toDeque assert deq[0] == deq.peekFirst and deq.peekFirst == 4 #assert deq[^1] == deq.peekLast and deq.peekLast == 789 |