summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorJake Leahy <jake@leahy.dev>2023-06-10 22:43:32 +1000
committerGitHub <noreply@github.com>2023-06-10 14:43:32 +0200
commitd3af0882cff6d1d4cbaf669005f6463d72e5be27 (patch)
tree426ea87725d1d96a9713b7a707875ce06c27a4d7
parentb2d77619757c73a8b14a8ccf127eaf3e630159cf (diff)
downloadNim-d3af0882cff6d1d4cbaf669005f6463d72e5be27.tar.gz
`BackwardsIndex` overload for `CacheSeq.[]` (#22043)
* Add `BackwardsIndex` support for `CacheSeq`

* Add changelog entry

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
-rw-r--r--changelogs/changelog_2_0_0.md1
-rw-r--r--lib/core/macrocache.nim13
2 files changed, 14 insertions, 0 deletions
diff --git a/changelogs/changelog_2_0_0.md b/changelogs/changelog_2_0_0.md
index e8dbbc27c..42c25946a 100644
--- a/changelogs/changelog_2_0_0.md
+++ b/changelogs/changelog_2_0_0.md
@@ -335,6 +335,7 @@
   + Added bindings to [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)
   and [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask).
   + Added `toDateString`, `toISOString`, `toJSON`, `toTimeString`, `toUTCString` converters for `DateTime`.
+- Added `BackwardsIndex` overload for `CacheSeq`.
 - Added support for nested `with` blocks in `std/with`.
 
 
diff --git a/lib/core/macrocache.nim b/lib/core/macrocache.nim
index ffd07abb1..39999fa11 100644
--- a/lib/core/macrocache.nim
+++ b/lib/core/macrocache.nim
@@ -127,6 +127,19 @@ proc `[]`*(s: CacheSeq; i: int): NimNode {.magic: "NcsAt".} =
       mySeq.add(newLit(42))
       assert mySeq[0].intVal == 42
 
+proc `[]`*(s: CacheSeq; i: BackwardsIndex): NimNode =
+  ## Returns the `i`th last value from `s`.
+  runnableExamples:
+    import std/macros
+
+    const mySeq = CacheSeq"backTest"
+    static:
+      mySeq &= newLit(42)
+      mySeq &= newLit(7)
+      assert mySeq[^1].intVal == 7  # Last item
+      assert mySeq[^2].intVal == 42 # Second last item
+  s[s.len - int(i)]
+
 iterator items*(s: CacheSeq): NimNode =
   ## Iterates over each item in `s`.
   runnableExamples: