javascriptnode.jsdecoding

Decoding a txt file [Javascript]


I am trying to create a function where it can read an encoded message from a .txt file and return it into a string. Basically, the format of the txt follows a number and a word so for example:

3 love
6 computers
2 dogs
4 cats
1 I
5 you

the first thing I want it to do is arrange the numbers in a pyramid order like so:

  1
 2 3
4 5 6

the numbers should match the words on the .txt file and once it's organized, the end of the pyramid should write out a sentence so for example using the above list 1: I 3: love 6: computers writes out "I love computers".

So far this is what I got but it's only returning one value and I do not know why

function decode(message_file) {
  const fs = require("fs");
  const data = fs.readFileSync(message_file, "utf8");
  const lines = data.split("\n").filter(Boolean);
  const message_words = [];
  let current_line = 1;
  let current_num = 1;
  for (const line of lines) {
    const [num, word] = line.split(" ");
    if (parseInt(num) == current_num) {
      message_words.push(word);
      current_line++;
      current_num = (current_line + 1) / 2;
    }
  }
  return message_words.join(" ");
}

const decoded_message = decode("message.txt");
console.log(decoded_message);

Solution

  • Your code only makes one pass through the lines in the file. If the number on the line matches current_num it gets returned. But that's an unusual coincidence so you don't get all the numbers.

    First create an array where the words are at indexes corresponding to the number in the file.

    Then write a loop that implements the number pyramid and outputs the words at the corresponding indexes in the array.

    function decode(data) {
      const lines = data.split("\n").filter(Boolean);
      const message_words = [];
      lines.forEach(line => {
        [index, word] = line.split(' ');
        message_words[parseInt(index)] = word;
      });
    
      let line_length = 1;
      let line_pos = 0;
      let output_string = '';
      for (let i = 1; i < message_words.length; i++) {
        output_string += message_words[i];
        line_pos++;
        if (line_pos >= line_length) {
          // Reached the end of the current line
          // Start a new line and make it one word longer
          output_string += '\n';
          line_pos = 0;
          line_length++;
        } else {
          output_string += ' ';
        }
      }
      return output_string;
    }
    
    console.log(decode(content));
    <script>
      let content = `3 love
    6 computers
    2 dogs
    4 cats
    1 I
    5 you`;
    </script>