Skip to content

Instantly share code, notes, and snippets.

@SimonHoiberg
Created November 14, 2020 14:49
Show Gist options
  • Save SimonHoiberg/a5645dd55d439e3872c6a63b249f1231 to your computer and use it in GitHub Desktop.
Save SimonHoiberg/a5645dd55d439e3872c6a63b249f1231 to your computer and use it in GitHub Desktop.
Get the last item given an Array, Set, Map or object.
const lastItem = (list) => {
if (Array.isArray(list)) {
return list.slice(-1)[0];
}
if (list instanceof Set) {
return Array.from(list).slice(-1)[0];
}
if (list instanceof Map) {
return Array.from(list.values()).slice(-1)[0];
}
if (!Array.isArray(list) && typeof list === "object") {
return Object.values(list).slice(-1)[0];
}
throw Error(`argument "list" must be of type Array, Set, Map or object`);
};
// Usage
const l1 = lastItem(["a", "b", "c"]);
// c
const l2 = lastItem(new Set(["d", "e", "f"]));
// f
const l3 = lastItem(
new Map([
["a", "x"],
["b", "y"],
["c", "z"]
])
);
// z
const l4 = lastItem({ a: "x", b: "y", c: "z" });
// z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment