Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterative writes #16

Open
lazarljubenovic opened this issue Apr 8, 2018 · 4 comments
Open

Iterative writes #16

lazarljubenovic opened this issue Apr 8, 2018 · 4 comments

Comments

@lazarljubenovic
Copy link
Contributor

Similarly to the reason conditionalWrite was introducted, it would be really nice if we were not forced to break the chain and introduce a for-of loop with a single writeLine call.

Something along the lines of the following would be great.

const indexes = [5, 9, 10, 15, 17]

writer
  .writeLine(`return [`)
  .iterateWriteLine(indexes, index => `this.array[${index}],`)
  .writeLine(`]`)
@dsherret
Copy link
Owner

dsherret commented Apr 8, 2018

I like this (and the other issue you opened), thanks!

It could probably be similar to the signature of Array.prototype.forEach. So currentValue[, index[, array].

@lazarljubenovic
Copy link
Contributor Author

Sounds good! I'd just change the naming to value, key and iterable/iteratee, to cover each of three big iteratees in JavaScript (Array#forEach, Map#forEach and Set#forEach). This will cover custom iterables, as well.

@lazarljubenovic
Copy link
Contributor Author

I looked around a bit in my code to see where I could apply this and there are only a few exceptions to the rule I've found: I always indent the block where I iterate.

The example I've given is not how you'd probably do it in a real project... Instead, it would be

const indexes = [5, 9, 10, 15, 17]

writer
  .writeLine(`return [`)
  .indentBlock(() => {
      writer.iterateWriteLine(indexes, index => `this.array[${index}],`)
  })
  .writeLine(`]`)

The chain is broken anyway and for such a short line you'd pretty much inline it anyway:

const indexes = [5, 9, 10, 15, 17]

writer
  .writeLine(`return [`)
  .indentBlock(() => {
      indexes.forEach(index => writer.writeLine(`this.array[${index}],`)
  })
  .writeLine(`]`)

🤔


PS. It's funny how iterate and forEach have exactly the same amount of characters. 😂

@dsherret
Copy link
Owner

dsherret commented Apr 8, 2018

Hmmm... good point. The only alternative I can think of is adding a .withEach or something like it:

writer
  .writeLine(`return [`)
  .withEach(indexes, index => writer.indent().writeLine(`this.array[${index}],`))
  .writeLine(`]`)

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

No branches or pull requests

2 participants