From 6f482ab9346230f8e9c24f71091bcd5ca2cb41f8 Mon Sep 17 00:00:00 2001 From: ee7 <45465154+ee7@users.noreply.github.com> Date: Fri, 7 Aug 2020 22:54:34 +0200 Subject: 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. --- lib/pure/collections/deques.nim | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'lib/pure/collections') 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 -- cgit 1.4.1-2-gfad0