Last Item
Get the last N items of an array or just the last one, faster than
Array.prototype.slice
/Array.prototype.at
.
Usage
The API is the same on all this platforms ✔️
Deno 🦕
import { lastItem } from "https://deno.land/x/last_item/mod.ts";
const numbers = [1, 2, 3, 4, 5];
lastItem(numbers); //=> 5
lastItem(numbers, 3); //=> [3, 4 , 5]
Node.js 🐢🚀
import { lastItem } from "@ultirequiem/last-item";
Browser 🌐
You can use any CDN 🔥
Eg 👉 ESM ↔️ SkyPack 🆚 Script Tag ↔️ JSDelivr
Alternatives
This is a utility module, which focuses on being faster than its native counterparts and similar modules.
In the vast majority of cases you should prefer Array.prototype.slice
or
Array.prototype.at
if performance is not an issue.
One of the biggest advantages of this module is also that it is packaged to be easy to use in various environments such as Node.js, Deno or the Browser.
Get Last Array Item
const abc = ["a", "b", "c"];
lastItem(abc); //=> "c"
abc.at(-1); //=> "c"
Get N Last Array Items
const animals = ["Tiger", "Horse", "Lion"];
lastItem(animals, 2); //=> ["Horse", "Lion"]
animals.splice(-2); //=> ["Horse", "Lion"]
Similar Modules
array-last
This module is also quite fast, so I am including it as an alternative, I must mention that it has some bugs and open pull requests for several years and there seems to be no activity.
The biggest drawback of this module in my opinion is the poor error handling and it’s strange behavior, here are some things I noticed.
This module would throw a
RangeError
This module would throw a
TypeError
last(["a", "b", "c"], 4); //=> [ undefined, 'a', 'b', 'c' ]
This module would throw a
RangeError
This module would throw a
RangeError
Benchmarks
Check the benchmark code on bench.ts
⚡
benchmark time (avg) (min … max) p75 p99 p995
-------------------------------------------------- -----------------------------
Slice 44.75 ns/iter (39.73 ns … 801.56 ns) 42.69 ns 79.87 ns 80.45 ns
At 81.23 ns/iter (79.83 ns … 104.44 ns) 81.35 ns 94.27 ns 94.68 ns
Array Last 13.93 ns/iter (13.65 ns … 29.26 ns) 13.7 ns 15.01 ns 15.38 ns
Last Item 14.21 ns/iter (12.7 ns … 19.77 ns) 14.87 ns 15.37 ns 15.51 ns
Version 0.1.2
Benchmarks are run on GitHub Actions on each commit, you can see the latest runs here.
Documentation
Is hosted on Deno Doc 📄
Support
Open an Issue, I will check it a soon as possible 👀
If you want to hurry me up a bit send me a tweet 😆
Consider supporting me on Patreon if you like my work 🙏
Don’t forget to start the repo ⭐
Authors
Eliaz Bobadilla - Creator and Maintainer 💪
See also the full list of contributors who participated in this project ✨
Versioning
We use Semantic Versioning. For the versions available, see the tags 🏷️
Licence
Licensed under the MIT License 📄