code-block-writer
code-block-writer copied to clipboard
Iterative writes
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(`]`)
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].
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.
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:
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(`]`)