3
\$\begingroup\$

My goal is to get a list of related statementIds in order of most repeated.

In my database I have stems(Words):

+---------+-----------------+
|  Stem   |   StatementId   |
+---------+-----------------+
| Hello   | [2,46,62]       |
| Good    | [1,123,45]      |
| Morning | [23,2436,12312] |
+---------+-----------------+

My steps:

  1. Get all statementIds [6, 86],[6],[4],[3, 86],[...]
  2. Create an empty object, and everytime i see a number,increase its value (or set to 1 if it hasen't been seen before)  {2: 1, 3: 4, 4: 1, 6: 11, 85: 1, 86: 5, 87: 1, 89: 1}

  3. Sort the object by the attribute and put it in an array of relevancy.  ["6", "86", "3", "89", "87", "85", "4", "2"]

Full code:

getAllStatementIdFromStem = async (stems: string[]) => {
    const ids: { [key: number]: number } = {};
    await this.getBulkStem(stems).toArray((stems: Stem[]) =>
      stems.map(({ statements }) =>
        statements.forEach((statementId: number) => {
          typeof ids[statementId] === "undefined"
            ? (ids[statementId] = 1)
            : ids[statementId]++;
        })
      )
    );
    return Object.entries(ids)
      .sort((a, b) => a[1] - b[1])
      .reverse()
      .map(x => x[0]);
  };

Could I be doing something more effectively? I feel like I am doing way too many extra steps.

\$\endgroup\$
2
  • \$\begingroup\$ Couple of questions: are statement IDs and sentence IDs the same? Can you provide an end to end example, e.g. for X input you should get Y output. Means that I can step through the code on my end, using your input, and see if any steps can be optimised. \$\endgroup\$ – Adam Taylor Feb 19 '20 at 0:25
  • \$\begingroup\$ Updated the names. input = [ [1], [65, 85, 86, 87, 88, 89], [2], [1, 2]] output = [1, 2, 89, 88, 87, 86, 85, 65] \$\endgroup\$ – user12904402 Feb 20 '20 at 12:38
2
\$\begingroup\$

Overall looks good. I think following improvements can be suggested.

1.Instead of this

typeof ids[statementId] === "undefined"
  ? (ids[statementId] = 1)
  : ids[statementId]++;

How about this for more readability

ids[statementId] = (ids[statementId] || 0) + 1;

2.Instead of doing sort and immediately reverse. You can change sort function (with descending order) so that you can avoid reverse call.

\$\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.