From df8e0e7f0c3a2e340c625d8c55d9105da106dbfd Mon Sep 17 00:00:00 2001 From: Dean Eigenmann <7621705+decanus@users.noreply.github.com> Date: Thu, 2 Apr 2020 12:09:29 +0200 Subject: feature/count (#13837) --- changelog.md | 2 +- lib/pure/collections/sequtils.nim | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index 7dccc20b9..32f6e0a1b 100644 --- a/changelog.md +++ b/changelog.md @@ -124,9 +124,9 @@ echo f through an SSL-wrapped `Socket`/`AsyncSocket`. - Added `distinctBase` overload for values: `assert 12.MyInt.distinctBase == 12` - Added `browsers.openDefaultBrowser` without URL, implements IETF RFC-6694 Section-3. +- Added `sequtils.countIt`, allowing for counting items using a predicate. - Added `jsconsole.trace`, `jsconsole.table`, `jsconsole.exception` for JavaScript target. - ## Library changes - `asyncdispatch.drain` now properly takes into account `selector.hasPendingOperations` diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index e32c784c6..0cc91b0d0 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -600,6 +600,25 @@ template keepItIf*(varSeq: seq, pred: untyped) = inc(pos) setLen(varSeq, pos) +since (1, 1): + template countIt*(s, pred: untyped): Natural = + ## Returns a count of all the items that fulfilled the predicate. + ## + ## The predicate needs to be an expression using + ## the ``it`` variable for testing, like: ``countIt(@[1, 2, 3], it > 2)``. + ## + runnableExamples: + let numbers = @[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + iterator iota(n: int): int = + for i in 0..