Skip to content
This repository has been archived by the owner on Mar 10, 2024. It is now read-only.

Add .firstItem for symmetry #27

Open
zocky opened this issue Aug 14, 2019 · 3 comments
Open

Add .firstItem for symmetry #27

zocky opened this issue Aug 14, 2019 · 3 comments

Comments

@zocky
Copy link

zocky commented Aug 14, 2019

I realize that this would be a trivial syntactic sugar for array[0], but

  • Symmetry is good. It makes the language easier to learn and the code easier to write and read.
  • Annoying the programmer is bad. If you often type .lastItem you will automatically start typing .firstItem even if it doesn't exist.
  • When using arrays with .shift() and .pop() (as opposed to iteration by index), using .firstItem and .lastItem makes the code more readable.
@Zarel
Copy link

Zarel commented Aug 14, 2019

Periodic reminder that .get(-1) (#23) solves this problem. ;)

@cyberixae
Copy link

cyberixae commented Nov 22, 2019

I like this idea. I think it makes code more readable since you don't need to figure out if the [0] might be the first item by accident. The main problem with [0] is that you don't know if the original programmer intended to type [1] or if she was expecting the index to change in the future. Where as firstItem communicates clearly that the index should never change.

I even think we should have firstIndex for similar reasons. Also, at one point in my life I was programming with both JavaScript and Lua and array indexing of arrays was different between the languages. While this is perhaps not common it would be nice to be able to state what you mean rather than having to remember technical details about how the indexing works. Usually you could just use map, forEach and similar constructs that do not depend on magic numbers.

@zakhenry
Copy link

This also reads more fluently with the common pattern of chaining array prototype methods together,

compare

function shortestWord(words) {
	return words.filter(word => word.length > 0)
				.sort((a, b) => a.length - b.length)
				.firstItem()
}

with

function shortestWord(words) {
	return words.filter(word => word.length > 0)
				.sort((a, b) => a.length - b.length)
				[0]
}

the former is a lot more readable as the dangling [0] doesn't seem to fit with the flow.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants