code-block-writer icon indicating copy to clipboard operation
code-block-writer copied to clipboard

Iterative writes

Open lazarljubenovic opened this issue 7 years ago • 4 comments

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(`]`)

lazarljubenovic avatar Apr 08 '18 17:04 lazarljubenovic

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].

dsherret avatar Apr 08 '18 18:04 dsherret

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 avatar Apr 08 '18 18:04 lazarljubenovic

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(`]`)

:thinking:


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

lazarljubenovic avatar Apr 08 '18 19:04 lazarljubenovic

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(`]`)

dsherret avatar Apr 08 '18 23:04 dsherret