summary refs log tree commit diff stats
path: root/lib/pure
diff options
context:
space:
mode:
authoree7 <45465154+ee7@users.noreply.github.com>2020-08-07 22:54:34 +0200
committerGitHub <noreply@github.com>2020-08-07 22:54:34 +0200
commit6f482ab9346230f8e9c24f71091bcd5ca2cb41f8 (patch)
tree34f648e222f9cfbaa34297c2cff3674a79284951 /lib/pure
parenta528382e057780845585f0befa6da505462a622e (diff)
downloadNim-6f482ab9346230f8e9c24f71091bcd5ca2cb41f8.tar.gz
deques.nim: Refactor the `toDeque` functionality (#15166)
This commit polishes the new proc introduced by d9ed816b10a6.

Changes:
- Rename to `toDeque` for more consistency with well-known procs like
  `toHashSet` and `toTable`.
- Rename the `openArray` parameter. The name `arr` was potentially less
  clear given that the proc can be used with a seq (or string).
- Add a `since` annotation.
- Reword the doc comment, and clarify that ordering is preserved.
- Add runnableExamples.
- Add "see also" cross linking between `initDeque` and `toDeque`.
- Remove duplicate `nextPowerOfTwo`. The `initImpl` template already
  includes it.
- Implement the proc using the `items` iterator, rather than indexing.
  This matches the implementation of `sets.toHashSet` and
  `tables.toTable`.
- Add a test within `when isMainModule`.
- Add a changelog entry.
Diffstat (limited to 'lib/pure')
-rw-r--r--lib/pure/collections/deques.nim23
1 files changed, 18 insertions, 5 deletions
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