-
-
Save SimonHoiberg/a5645dd55d439e3872c6a63b249f1231 to your computer and use it in GitHub Desktop.
Get the last item given an Array, Set, Map or object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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