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

Filling Array with Alphanumeric values

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

Problem

I've done a function that does the following :

  • It takes an argument length that it will be the length of the result array.



  • The Array should start with alphabet values first : ['A', 'B', 'C', ...]



  • If the length of the Array is greater than 26 (The number of letters) it should look like : ['A', 'B', 'C', ..., 'A1', 'B1', 'C1'], if greater than 52 : ['A', 'B', 'C', ..., 'A1', 'B1', 'C1', ..., 'A2', 'B2', 'C2'] and so on.



The following function i've done uses some new Array features :



let getNums = length =>{

if(length String.fromCharCode(i + 65));

let nums = Math.floor( length / 26 );
nums = nums == 0 ? 0 : nums - 1;
let rest = length - (26 * (nums + 1) );

return [...Array.from({length : 26}, (el, i)=> String.fromCharCode(i + 65)),
...Array.from({length : nums}, (el, i)=> i + 1)
.reduce( (a, b)=> a.concat(Array.from({length : 26},
(el, i)=> String.fromCharCode( i + 65 ) + b ) ),
[]),
...Array.from({length : rest}, (el, i)=> String.fromCharCode(i + 65) + (nums + 1) )
];

}

console.log(getNums(53));




This works, but I'm worried about the efficiency of this function because several Arrays are created and concatenated. So, this would be better if done with loops and some if...else statements?

Solution

Unless you confirm the speed is a problem in the code profiler, there's no need to optimize it.

And if you want to make js code run fast, just avoid using one of the most expensive operations: invocation of a callback/function (you had 6 of them), maximize the workload inside the engine by using existing native functions and minimizing amount of time spent in interpreted code.

In this case switching to string manipulation makes the code 2.5 times faster as measured here on 10k repetitions.

let getNums = length => {
    var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = letters.substr(0, length).split('');
    for (var i = 1, numberedCount = Math.floor((length - 1)/26); i <= numberedCount; i++) {
        length -= letters.length;
        result.push.apply(result,
            letters.substr(0, length).replace(/./g, '%%CODEBLOCK_0%%amp;' + i + ' ').trim().split(' '));
    }
    return result;
}

Code Snippets

let getNums = length => {
    var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = letters.substr(0, length).split('');
    for (var i = 1, numberedCount = Math.floor((length - 1)/26); i <= numberedCount; i++) {
        length -= letters.length;
        result.push.apply(result,
            letters.substr(0, length).replace(/./g, '$&' + i + ' ').trim().split(' '));
    }
    return result;
}

Context

StackExchange Code Review Q#138953, answer score: 2

Revisions (0)

No revisions yet.