Last Item
Get the last item of an array, faster than
Array.prototype.slice
/Array.project.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 π