JavaScript的两种解法:第一种是接收到整个字符串后,对其进行trim,取最后一个空格的索引,进而得到最后一个单词的长度。这种方法非常简单直观,但是数据量很大的话,生成一个长字符串未免对内存太过粗暴。另一种是每接收到一个字符,就计算一次最后一个单词的长度,没有第一种方法的缺点,但是监听函数执行次数超多,好在每次操作都非常简单。

const readline = require('readline');

// This is automatically called by any readline instance on its input if the input is a terminal.
readline.emitKeypressEvents(process.stdin);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// get last word length by listening line event on readline instance
const listenLine = () => {
  rl.addListener('line', (input) => {
    const trimedInput = input.trim();
    const lastSpaceIndex = trimedInput.lastIndexOf(' ');
    const lastWordLength =
      lastSpaceIndex === -1
        ? trimedInput.length
        : trimedInput.length - lastSpaceIndex - 1;
    console.log(lastWordLength);
    rl.close();
  });
};

const isSpace = (character) => {
  return character === ' ';
};

const isEndOfLine = (character) => {
  return ['\n', '\r', '\r\n'].includes(character);
};

// get last word length by listening keypress event on stdin
const listenKerpress = () => {
  let lastWordLenth = 0;
  let previousCharacter = '';
  let currentCharacter = '';

  process.stdin.on('keypress', (character) => {
    previousCharacter = currentCharacter;
    currentCharacter = character;

    if (isEndOfLine(currentCharacter)) {
      console.log(lastWordLenth);
      rl.close();
      return;
    }

    if (!isSpace(currentCharacter)) {
      if (isSpace(previousCharacter)) {
        lastWordLenth = 1;
      } else {
        lastWordLenth += 1;
      }
    }
  });
};

// listenLine();
listenKerpress();