mirror of
https://github.com/nim-lang/Nim.git
synced 2026-02-15 15:44:14 +00:00
feature/count (#13837)
This commit is contained in:
@@ -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`
|
||||
|
||||
@@ -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..<n: yield i
|
||||
assert numbers.countIt(it < 0) == 3
|
||||
assert countIt(iota(10), it < 2) == 2
|
||||
|
||||
var result = 0
|
||||
for it {.inject.} in s:
|
||||
if pred: result += 1
|
||||
result
|
||||
|
||||
proc all*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool =
|
||||
## Iterates through a container and checks if every item fulfills the
|
||||
## predicate.
|
||||
|
||||
Reference in New Issue
Block a user