Created
August 13, 2016 03:22
-
-
Save tizmagik/19ba6516064a046a37aff57c7c65c9cd to your computer and use it in GitHub Desktop.
ES6 Last Item in Map()
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
// Since ES6 Map()'s' retain their order of insertion, it can sometimes be useful to get the last item or value inserted: | |
export const getLastItemInMap = map => Array.from(map)[map.size-1] | |
export const getLastKeyInMap = map => Array.from(map)[map.size-1][0] | |
export const getLastValueInMap = map => Array.from(map)[map.size-1][1] | |
// Obviously getLastKey and getLastValue can reuse getLastItem, but for maximum portability I opted for verbosity. |
it will need to iterate through the whole collection when you only need the last?
do you have a better idea for javascript Map?
except hiding the map behind a proxy object, and tracking the set
and delete
calls
Nice 😝
Thank you so much!
const [lastKey, lastValue] = [...map].at(-1) || []
// Key only
const [lastKey] = [...map].at(-1) || []
// Value only
const [, lastValue] = [...map].at(-1) || []
// set
const lastValue = [...set].at(-1)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is probably slower as it will need to iterate through the whole collection when you only need the last?