3
\$\begingroup\$

I have a code based on the following problem "Mapping phone numbers to names", the problem is that when they are going to process large data(+100.000) the program ends by timeout. my code and problem is this, how can I optimize my code to consume less time?

my code

function processData(input) {
  var r=input.split(/\n/),o=Number(r[0]),c=r.length-1,x=[];
  r.splice(0,o+1);
  r.forEach((l)=>{
      var rx=new RegExp(l+"\\s(\\d+)"),o=input.match(rx);
      console.log(o==null?"Not found":l+"="+o[1]);
  });
} 

Example Input

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Example Output

sam=99912222
Not found
harry=12299933

The program generates timeout in the following case

BIG Example Input and output Thanks

\$\endgroup\$
  • 3
    \$\begingroup\$ Pay heed to the motto of the day: Dictionaries and Maps. \$\endgroup\$ – greybeard Jun 26 '17 at 7:24
  • \$\begingroup\$ include an example of your data \$\endgroup\$ – Hitmands Jun 26 '17 at 10:12
2
\$\begingroup\$

Naming

Single character name is a bad practice. Use the descriptive names for variables.

r => rows
o => noOfRecords
c => noOfRows
x => ...

They are not searchable and can be easily confused with numbers. For example, l and 1, 0 and o/O.

Dead/Unused Code

Variables c and x are not used and thus can be removed.

Overriding Variables

<opinion-based>Variable o is used to get the first line in the file and then inside forEach it is again used to store the match result. This will work fine, but will also confuse other users(or you after few months). The variables should be used for single-purpose.</opinion-based>

Slice down input data

Inside forEach, input data is used to search for the name. input here is complete data with the number of records on the first line, name-numbers and then names. This data can be sliced down to keep only name-number. This will reduce the data to work on and will improve the performance.

var rows = input.split(/\n/);
var nameAndNumbers = rows.slice(1, numberOfRows + 1);

and use nameAndNumbers to search name from.


As greybeard mentioned in comment, you should use object/Map to store the name and number.

function processData(input) {
    var rows = input.split(/\n/);
    var numberOfRows = Number(rows[0]);

    var nameAndNumbers = rows.slice(1, numberOfRows + 1);
    var names = rows.slice(numberOfRows + 1);

    var phoneBook = {};
    nameAndNumbers.forEach(function(number) {
        var data = number.split(' ');
        phoneBook[data[0]] = data[1];
    });

    return names.map(name => phoneBook[name] ? name + '=' + phoneBook[name] : 'Not Found').join('\n');
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.