HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Printing staircase revisited

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
revisitedstaircaseprinting

Problem

What can be more elegant ways to solve the given problem.

#
   ##
  ###
 ####


Code:

function StairCase(n) {
    for (var i = 1; i <= n; i++) {
        var col = i;
        for(var j = 1; j <= n - col; j++) {
            process.stdout.write(' ');
        }
        for(var j = 1; j <= col; j++) {
            process.stdout.write('#');
        }
        process.stdout.write('\n');
    }

}

Solution

JavaScript function names should start with a lowercase character, and "staircase" is one compound word in English.

Since every line is nearly the same, and only one character changes at a time, you should take advantage of that and use an array as a buffer.

function staircase(n) {
    var line = Array(n + 1).fill(' ');
    line[n] = '\n';
    for (var i = n - 1; i >= 0; i--) {
        line[i] = '#';
        process.stdout.write(line.join(''));
    }
}

Code Snippets

function staircase(n) {
    var line = Array(n + 1).fill(' ');
    line[n] = '\n';
    for (var i = n - 1; i >= 0; i--) {
        line[i] = '#';
        process.stdout.write(line.join(''));
    }
}

Context

StackExchange Code Review Q#135944, answer score: 11

Revisions (0)

No revisions yet.