Counting word frequency with my little JS function 🧐

Folks,
This code won’t count the frequency of a specific word:

function countWordOccurrence(inputs) {
  try {
    const wordToMatch = 'Suggestion';
    const text = inputs.data;
    const count = text.split(wordToMatch).length - 1;
    return [0, { result: count }];
  } catch (error) {
    return [1, { error: error.message }];
  }
}

Tested with my text pageVar that contains a text chapter and raw text in the inputs object :point_down:, nothing works. What am I missing?
image

You are missing a function call to your function. Here’s a working code:

function countWordOccurrence(input) {
  try {
    const wordToMatch = 'Suggestion';
    const text = input.input1;
    const count = text.split(wordToMatch).length - 1;
    return [0, { result: count }];
  } catch (error) {
    return [1, { error: error.message }];
  }
}

return { result: countWordOccurrence(inputs) };

Which produces:

image

When you do countWordOccurrence(inputs), JS thinks that inputs is a function parameter, even if there is a variable named the same. So for demonstration purposes, I renamed it in my code and passed the inputs in a function call. Also note const text = input.input1;, your’s should be const text = input.data;.

You can fix your code by just adding return { result: countWordOccurrence(inputs) }; at the end.

Thanks!

Yet, brain freeze, how do I isolate the result 4 for my pageVar connected to success port?

EDIT: chatGPT4 helped me fix it:

function countWordOccurrence(inputs) {
  try {
    const wordToMatch = 'completion';
    const text = inputs.data;
    const count = text.split(wordToMatch).length - 1;
    return { result: count };
  } catch (error) {
    return { error: error.message };
  }
}
return countWordOccurrence(inputs);
1 Like