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');
}
Dictionaries and Maps
. \$\endgroup\$