Java – keep scroll positions on page by url [closed]

I am not good in Java, please help if you can.
Need to keep position on page, but different page means different position. Found a script for it and it works OK. There is problem, I have few pages with redirected to same page, but different URL (by RewriteRule), but the script takes it as one same URL.

RewriteRule page1.php detail.php
RewriteRule page2.php detail.php
RewriteRule page3.php detail.php

script:

document.addEventListener("DOMContentLoaded", function (event) {
    var scrollpos = localStorage.getItem("scrollpos");
    if (scrollpos) window.scrollTo(0, scrollpos);
});

window.onscroll = function (e) {
    localStorage.setItem("scrollpos", window.scrollY);
};

vue axios.post method is neither doing anything nor throwing an error

I have a vue frontend with a flask backend and in addition a c++ camera backend. All of this has been working before. Now I switched to another computer and I´m using a different camera backend and camera.
Now I run into this strange problem: When I press a frontend button, It first triggers the camera image acquisition, waits for the filepath and THEN it should do an axios.post to my backend api. But nothing happens. The Endpoint doesn´t get triggered and I don´t get any errors or responses.

When I enter the debugger and trigger the whole axios.post statement manually, It works fine!

Any ideas what I can do?

  • Working on a Windows Machine
  • npm version 10.9.2
  • vue version 3.3.4 (i think)
  • axios version 1.7.9
async function startImgAnalysis() {
  updateBusy(true);

  recordStore.setRecordName(recordName.value);
  await recordStore.createSnapshot(recordName.value, recordType);

  await sleep(500); // we need a pause here, to make sure the image was really written 
  var path = await recordStore.getLatestRecord(recordName.value, recordType);

  if(!path){
    errorStore.setError("Analysis could not be started!", "The file path is empty.")
  } else{
      //debugger;
      console.log(path);   // this works!
      axios.post("analyze/start", {'path': path})   // nothing happens till I do it manually via debugger
          .then((res) => {
            let statuspath = res.headers.get('statusid');
            analysisInProgress.value=true;
            updateProgress(statuspath);
          })
          .catch((err) => {       //No errors are logged
            console.error(err);
            updateBusy(false);
          });
    }
}

Angular 19 change innerHTML of an dynamic created DIV

i’ve following situation:
i’m create with an api dynamic div for drag and drop.

Drag & Drop works very well. now when i do a double Click i want to change the HTML content of this div. How can i do that in Angular?

in javascript you can use getElementById.innerHTML

But it seems this is not the Angular way.

How to display multiple data in HTML? [closed]

I have this code, which represents the data for one actor:

<section class="container">
        <div class="row row-cols-3 justify-content-center">
            <div class="row">
                <img src="../images/HoytevanHoytema.jpg" alt="Actor" />
                <div class="separador">
                    <h2>ACTOR</h2>
                    <button class="vote-button">VOTAR</button>
                </div>
                <p>By FILM NAME</p>
            </div>
        </div>
    </section>

And I need to show data for 6 actors, for example. How I do it? I thought 3 options:

  • Statically: Write manually the data for the 6 actors.
  • Dinamically: Use a JSON with the information of he actors but, Isn’t it very inefficient to ask the server for “static” information about each actor?
  • Another method. I thought that there must be a way to dynamically load the HTML data into the server before sending it to the client.

Creating JavaScript to make Hover function on iOS [duplicate]

I’m working on this website and I don’t currently know how to test this on iOS for free. I’m trying JavaScript out. Should this function? Sorry, I think I’m still a little new. Thanks

            const navbarElement = document.querySelectorAll('.navbar .subnav #raiseup img.catalogue-img');

            navbarElement.addEventListener('touchstart', function(e) {
              e.preventDefault(); // Prevents the default touch behavior
              this.classList.toggle('hovered');
            });

            // Optional: Remove the class on touchend or touchcancel
            navbarElement.addEventListener('touchend', function() {
              this.classList.remove('hovered');
            });

            navbarElement.addEventListener('touchcancel', function() {
                this.classList.remove('hovered');
            });

jqgrid inline edit conflicts with form editing

I’m using free jqGrid form editing (navGrid) with also inline editing (inlineNav) only for editing using Enter and Esc keys.

  $('#gridId').jqGrid('navGrid','#pagerId',
    {edit: true, add: true, del: true, search: true, view: true, refresh: true})
  
  .jqGrid('inlineNav','#pagerId',
    {edit: true, add: false, save: false, cancel: false, editParams: {keys: true}});

Some problems arise when the user enters inline editing and forgets to accept or cancel it with the proper key (Enter or Esc).

If the refresh button is pressed, nothing is refreshed from the server, which may be OK taking into account that the inline editing is still pending to be accepted.

But if delete or add button are pressed, the grid reacts as if no inline editing where pending: deleting the row or showing a form to add a record, respectively.

Also, if some columns have search attribute set to true, you can fill search fields in the tool bar but nothing happens when you accept them pressing Enter key ( nothing is sent to the server ).

All this may be confusing for the user who enters inline editing, but forgets to accept or cancel it and continues to operate on the grid.

I wonder if there is a way to prevent doing other operations on the grid when inline editing starts, the same way that when a form editing starts the modal dialog prevents doing other operations.

Thanks in advance for any clue.

What is the order of microtasks in multiple Promise chains?

Out of an academic interest I am trying to understand the order of microtasks in case of multiple Promise chains.

I. Two Promise chains

These execute in a predictable “zipped” way:

Promise.resolve()
  .then(log('a1'))
  .then(log('a2'))
  .then(log('a3'));

Promise.resolve()
  .then(log('b1'))
  .then(log('b2'))
  .then(log('b3'));
// a1 b1 ; a2 b2 ; a3 b3
// Here and in other output listings
// manually inserted semicolons ";" help illustrate my understanding.

II. The first “a1” returns a Promise:

Promise.resolve()
  .then(() => {
    log('a1')();
    return Promise.resolve();
  })
  .then(log('a2'))
  .then(log('a3'));

Promise.resolve()
  .then(log('b1'))
  .then(log('b2'))
  .then(log('b3'));
// a1 b1 ; b2 ; b3 a2 ; a3

As I understand, a new Promise returned from a then() has introduced a single extra microtask to resolve that Promise; which has also shifted the “A” then() to the end of the “loop”. This allowed both “b2” and “b3” to overtake.

III. Three Promise chains

Here’s the working code to try running, along with the helper functions:

const output = [];

const makeChain = (key, n = 5, trueStep = false) => {
  let p = Promise.resolve();
  const arrow = isArrow => isArrow ? '->' : '';
  for (let i = 1; i <= n; i++) {
    const returnPromise = trueStep === i;
    const afterPromise = trueStep === i - 1;
    p = p.then(() => {
      output.push(`${arrow(afterPromise)}${key}${i}${arrow(returnPromise)}`);
      if (returnPromise) return Promise.resolve();      
    });
  }
  return p.catch(console.error);
};

// ----- cut line for this and next tests -----

Promise
  .all([
    makeChain('a', 3),
    makeChain('b', 3),
    makeChain('c', 3),
  ])
  .then(() => console.log(output.join(' ')));

// a1 b1 c1 ; a2 b2 c2 ; a3 b3 c3

So far so good: a “zip” again.

IV. Return Promise at “a1” step

(skipping the helper funciton)

Promise
  .all([
    makeChain('a', 3, 1),
    makeChain('b', 3),
    makeChain('c', 3),
  ])
  .then(() => console.log(output.join(' ')));
// a1-> b1 c1 ; b2 c2 ; b3 c3 ->a2 ; a3

Looks like the same behavior: “A1” introduced a single extra microtask + jumped to the tail of the “loop”.

V. “c4” also returns a Promise:

Promise
  .all([
    makeChain('a', 7, 1),
    makeChain('b', 7),
    makeChain('c', 7, 4),
  ])
  .then(() => console.log(output.join(' ')));

// a1-> b1 c1 ; b2 c2 ; b3 c3 ->a2 ; b4 c4-> a3 ; b5 a4 ; b6 a5 b7 ->c5 ; a6 c6 ; a7 c7

Two questions

  1. In the last test I cannot explain the order after “dispatching” the “c4”: why did the “b7” overtook the “c5” then()?

  2. Where can I read about the rules behind the order of the microtasks in the PromiseJobs queue?

Error, exports in common package not found when upgrading typescript from 3.7.2 to 4.4.4

I am trying to upgrade my typescript version from 3.7.2 to 4.4.4. The reason for the upgrade is because I want to use winston 3.7.2 which uses logform 2.5.x which requires typescript version >= 4.4.

This is my tsconfig.json. I’ve tried modifying it in various ways, such as trying
different values for target, lib, moduleResolution, baseUrl, and paths.

{
  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "lib": ["es6", "dom"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "moduleResolution": "node",
    "resolveJsonModule": true
  },
  "exclude": ["node_modules", "dist"],
  "include": ["src/**/*", "tests/**/*"]
}

This is my package.json

{
  "name": "@corp/serverless",
  "version": "1.1.0",
  "description": "aws serverless infrastructure",
  "main": "index.js",
  "scripts": {
    "build": "rm -rf .build && yarn serverless package --package ./dist",
    "lint": "eslint --ext .ts src",
    "migrate": "rm -rf .build && yarn sls invoke local --function postgresMigration -d '{ "migration": true, "orgSync": true, "seed": true }'",
    "start": "NODE_ENV=local yarn serverless offline --skipCacheInvalidation start",
    "test": "yarn jest",
    "test:ci": "yarn lint && yarn type-check && yarn test --coverage --maxWorkers=1",
    "type-check": "tsc --traceResolution"
  },
  "keywords": [
    "amazon-web-service"
  ],
  "author": "versett inc",
  "license": "UNLICENSED",
  "dependencies": {
    "@corp/common": "^1.0.0",
    "@types/object-hash": "^1.3.1",
    "agentkeepalive": "^4.1.0",
    "async": "^3.1.1",
    "aws-lambda-graphql": "1.0.0-alpha.19",
    "dataloader": "^2.0.0",
    "graphql": "14.5.8",
    "graphql-subscriptions": "^1.0.0",
    "http-status-codes": "^1.4.0",
    "ioredis": "^4.19.4",
    "jsonwebtoken": "^8.5.1",
    "jwks-rsa": "^1.6.0",
    "jwt-decode": "^2.2.0",
    "knex": "^0.21.1",
    "mime-types": "^2.1.27",
    "moment-timezone": "^0.5.33",
    "nanoid": "^2.1.10",
    "object-hash": "^2.0.1",
    "pg": "^8.2.1",
      "winston": "^3.2.1"
  },
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/plugin-proposal-class-properties": "^7.7.0",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-typescript": "^7.7.2",
    "@types/async": "^3.0.7",
    "@types/aws-lambda": "^8.10.36",
    "@types/http-status-codes": "^1.2.0",
    "@types/jest": "^24.9.0",
    "@types/nanoid": "^2.1.0",
    "@types/node": "^12.12.8",
    "@types/node-fetch": "^2.5.3",
    "@types/pg": "^7.14.1",
    "@types/request": "^2.48.4",
    "@typescript-eslint/eslint-plugin": "^2.6.1",
    "@typescript-eslint/parser": "^2.8.0",
    "@versett/eslint-plugin-versett": "^0.18.1",
    "ajv": "^6.11.0",
    "aws-sdk": "^2.799.0",
    "aws-sdk-mock": "^4.5.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.6.0",
    "eslint-config-prettier": "^6.7.0",
    "eslint-import-resolver-typescript": "^2.0.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jest": "^23.0.4",
    "eslint-plugin-prettier": "^3.1.1",
    "jest": "^24.9.0",
    "mssql": "^6.0.1",
    "mysql": "^2.17.1",
    "mysql2": "^2.1.0",
    "prettier": "^1.19.1",
    "serverless": "^1.57.0",
    "serverless-dotenv-plugin": "^2.1.1",
    "serverless-jetpack": "^0.11.2",
    "serverless-offline": "^5.12.0",
    "serverless-offline-dynamodb-streams": "^3.0.2",
    "serverless-offline-kinesis": "^3.0.1",
    "serverless-plugin-common-excludes": "^3.0.0",
    "serverless-plugin-include-dependencies": "^4.0.0",
    "serverless-plugin-typescript": "^1.1.9",
    "sqlite3": "5.1.7",
    "ts-jest": "^24.2.0",
    "typescript": "^3.7.2"
  }
}

In the bottom of this file, I tried changing "typescript": "^3.7.2" to "typescript": "^4.4.4" as well as other versions like 5.8.2. However, after making that change, I get errors where types defined in my common package @corp/common can no longer be found.

An example of this error is error EventNotification not found in '@corp/common'. The complete logs are shown below.

What I’ve done:

  • I’ve confirmed these dependencies exist and are being exported and imported correctly, and the issues only arise after changing the typescript version.
  • I added the following to my paths in tsconfig.json : "@corp/common": ["../common/src/*"]
  • I added the following to tsconfig.json : baseUrl : '.'
  • I tried changing target and lib in tsconfig.json to : ES2020
  • I tried setting moduleResolution to nodenext
  • I tried several other things as well, just iterating and seeing what would happen
@corp/serverless: $ yarn lint && yarn type-check && yarn test --coverage --maxWorkers=1
@corp/serverless: $ eslint --ext .ts src
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/generateHeartbeat.ts
@corp/serverless:   4:3  error  EventNotification not found in '@corp/common'      import/named
@corp/serverless:   5:3  error  PigNotification not found in '@corp/common'        import/named
@corp/serverless:   6:3  error  SignatureNotification not found in '@corp/common'  import/named
@corp/serverless:   7:3  error  TrainNotification not found in '@corp/common'      import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/mirrorEvent.ts
@corp/serverless:   2:10  error  EventNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processEventData.ts
@corp/serverless:   2:10  error  EventNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processEventSignatureData.ts
@corp/serverless:   2:10  error  SignatureNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processPigData.ts
@corp/serverless:     2:3   error    PigNotification not found in '@corp/common'     import/named
@corp/serverless:     3:3   error    SubscriptionType not found in '@corp/common'    import/named
@corp/serverless:     4:3   error    PigStatusValues not found in '@corp/common'     import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processPigEvent.ts
@corp/serverless:     1:10  error    PigStatusValues not found in '@corp/common'  import/named
@corp/serverless:     1:27  error    PigNotification not found in '@corp/common'  import/named
@corp/serverless:     1:44  error    gqlType not found in '@corp/common'          import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processTrainData.ts
@corp/serverless:     2:3   error    TrainNotification not found in '@corp/common'   import/named
@corp/serverless:     3:3   error    SubscriptionType not found in '@corp/common'    import/named
@corp/serverless:     4:3   error    TrainStatusValues not found in '@corp/common'   import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processTrainEvent.ts
@corp/serverless:     1:10  error    TrainStatusValues not found in '@corp/common'  import/named
@corp/serverless:     1:29  error    TrainNotification not found in '@corp/common'  import/named
    @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventMirror/index.ts
@corp/serverless:    4:10  error    EventTableRecord not found in '@corp/common/'     import/named
@corp/serverless:    4:28  error    EventMirrorComments not found in '@corp/common/' /home/circleci/repo/packages/serverless/src/graphqlApi/mutations/pigTracking.ts
@corp/serverless:   2:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/mutations/trainTracking.ts
@corp/serverless:   2:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/events.ts
@corp/serverless:   1:30  error  Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/named
@corp/serverless:   2:10  error  gqlType not found in '@corp/common'                                                                             import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/fakeLeak.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/pig.ts
@corp/serverless:     2:10  error    gqlType not found in '@corp/common'                                                                             import/named
@corp/serverless:     2:19  error    PigStatusValues not found in '@corp/common'                                                                     import/named
@corp/serverless:     3:30  error    Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/named
@corp/serverless:   103:16  warning  Identifier 'run_id' is not in camel case                                                                           @typescript-eslint/camelcase
@corp/serverless:   103:31  warning  Identifier 'pipeline_id' is not in camel case                                                                      @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/reports.ts
@corp/serverless:    1:10  error    gqlType not found in '@corp/common'             import/named
@corp/serverless:   54:9   warning  Identifier 'organization_id' is not in camel case  @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/summary.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/queries/train.ts
@corp/serverless:     2:10  error    gqlType not found in '@corp/common'                                                                             import/named
@corp/serverless:     2:19  error    TrainStatusValues not found in '@corp/common'                                                                   import/named
@corp/serverless:     3:30  error    Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/named
@corp/serverless:   103:16  warning  Identifier 'run_id' is not in camel case                                                                           @typescript-eslint/camelcase
@corp/serverless:   103:31  warning  Identifier 'pipeline_id' is not in camel case                                                                      @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/auditLog.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/events.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/fakeLeak.ts
@corp/serverless:   4:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/index.ts
@corp/serverless:   3:51  error  Parse errors in imported module './organizations': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/organizations.ts
@corp/serverless:   0:0  error  Parsing error: Cannot read properties of undefined (reading 'map')
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/pigTracking.ts
@corp/serverless:   2:10  error  SubscriptionType not found in '@corp/common'  import/named
@corp/serverless:   2:28  error  PigStatusValues not found in '@corp/common'   import/named
@corp/serverless:   2:45  error  gqlType not found in '@corp/common'           import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/reports.ts
@corp/serverless:   8:10  error  gqlType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/summary.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'           import/named
@corp/serverless:   1:19  error  SubscriptionType not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/resolvers/trainTracking.ts
@corp/serverless:   2:10  error  SubscriptionType not found in '@corp/common'   import/named
@corp/serverless:   2:28  error  TrainStatusValues not found in '@corp/common'  import/named
@corp/serverless:   2:47  error  gqlType not found in '@corp/common'            import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/types/resolverTypes.ts
@corp/serverless:   1:10  error  TokenUserInfo not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/graphqlApi/utils/queries.ts
@corp/serverless:   1:10  error  gqlType not found in '@corp/common'                                                                             import/named
@corp/serverless:   2:30  error  Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/heartbeatHandler/processHeartbeatData.ts
@corp/serverless:   3:10  error  HeartbeatNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/heartbeatHandler/processSummaryData.ts
@corp/serverless:   2:10  error  SummaryNotification not found in '@corp/common'  import/named
@corp/serverless:   2:31  error  SubscriptionType not found in '@corp/common'     import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/postgresMigration/organizationSync/syncOrganizationSqlCmd.ts
@corp/serverless:   2:18  error    Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default
@corp/serverless:   2:18  warning  Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default-member
@corp/serverless: /home/circleci/repo/packages/serverless/src/postgresMigration/organizationSync/syncPipelineSqlCmd.ts
@corp/serverless:   2:18  error    Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default
@corp/serverless:   2:18  warning  Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default-member
@corp/serverless: /home/circleci/repo/packages/serverless/src/reportHandler/index.ts
@corp/serverless:   27:7  warning  Identifier 'organization_id' is not in camel case  @typescript-eslint/camelcase
@corp/serverless:   29:7  warning  Identifier 'size_in_byte' is not in camel case     @typescript-eslint/camelcase
@corp/serverless:   30:7  warning  Identifier 'content_type' is not in camel case     @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/services/createAuditLog.ts
@corp/serverless:   31:5  warning  Identifier 'event_id' is not in camel case  @typescript-eslint/camelcase
@corp/serverless:   38:5  warning  Identifier 'pig_id' is not in camel case    @typescript-eslint/camelcase
@corp/serverless: /home/circleci/repo/packages/serverless/src/services/pgClient.ts
@corp/serverless:   1:18  error    Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default
@corp/serverless:   1:18  warning  Parse errors in imported module 'knex': Cannot read properties of undefined (reading 'map') (undefined:undefined)  import/no-named-as-default-member
@corp/serverless: /home/circleci/repo/packages/serverless/src/streamLog/formatLogs.ts
@corp/serverless:   2:10  error  LogLevel not found in '@corp/common'  import/named
@corp/serverless: ✖ 122 problems (57 errors, 65 warnings)
@corp/serverless: error Command failed with exit code 1.
@corp/serverless: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
@corp/serverless: error Command failed with exit code 1.
@corp/serverless: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
lerna ERR! yarn run test:ci exited 1 in '@corp/serverless'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.@corp/serverless: $ yarn lint && yarn type-check && yarn test --coverage --maxWorkers=1
@corp/serverless: $ eslint --ext .ts src
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: `parseForESLint` from parser `@typescript-eslint/parser` is invalid and will just be ignored
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/generateHeartbeat.ts
@corp/serverless:   4:3  error  EventNotification not found in '@corp/common'      import/named
@corp/serverless:   5:3  error  PigNotification not found in '@corp/common'        import/named
@corp/serverless:   6:3  error  SignatureNotification not found in '@corp/common'  import/named
@corp/serverless:   7:3  error  TrainNotification not found in '@corp/common'      import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/mirrorEvent.ts
@corp/serverless:   2:10  error  EventNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processEventData.ts
@corp/serverless:   2:10  error  EventNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processEventSignatureData.ts
@corp/serverless:   2:10  error  SignatureNotification not found in '@corp/common'  import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processPigData.ts
@corp/serverless:     2:3   error    PigNotification not found in '@corp/common'     import/named
@corp/serverless:     3:3   error    SubscriptionType not found in '@corp/common'    import/named
@corp/serverless:     4:3   error    PigStatusValues not found in '@corp/common'     import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processPigEvent.ts
@corp/serverless:     1:10  error    PigStatusValues not found in '@corp/common'  import/named
@corp/serverless:     1:27  error    PigNotification not found in '@corp/common'  import/named
@corp/serverless:     1:44  error    gqlType not found in '@corp/common'          import/named
@corp/serverless: /home/circleci/repo/packages/serverless/src/eventHandler/processTrainData.ts
@corp/serverless:     2:3   error    TrainNotification not found in '@corp/common'   import/named
@corp/serverless:     3:3   error    SubscriptionType not found in '@corp/common'    import/named
@corp/serverless:     4:3   error    TrainStatusValues not found in '@corp/common'   import/named  

Below is the package.json for my common package.

{
  "name": "@corp/common",
  "version": "1.0.0",
  "description": "Shared corp package",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "private": true,
  "author": "",
  "license": "ISC",
  "dependencies": {
    "uuid": "^3.3.3",
    "jwt-decode": "^2.2.0",
    "typescript": "^3.7.5"
  },
  "scripts": {
    "build": "yarn clean && yarn build:type && tsc",
    "clean": "rm -rf dist",
    "postinstall": "yarn build",
    "build:type": "graphql-codegen --config graphql-codegen.yml"
  },
  "devDependencies": {
    "@types/uuid": "^3.4.6",
    "@graphql-codegen/add": "^1.13.1",
    "@graphql-codegen/cli": "^1.13.1",
    "@graphql-codegen/import-types-preset": "^1.13.1",
    "@graphql-codegen/introspection": "1.13.1",
    "@graphql-codegen/typescript": "1.13.1"
  }
}

I noticed there were fields for main and types which seemingly had files being placed into the dist folder. So, I went back to my other tsconfig.json and set the following for paths.

"baseUrl": ".",
    "paths": {
  "@corp/common" : ["../common/dist"]
}

After doing that, I’m still seeing the same errors.

Admittedly, I’m very new to typescript and javascript and I’m not sure how to tackle the issue. Guidance would be very appreciated. Thank you.

AG-Grid v33+: JavaScript: Install via CDN, but don’t use CDN for themes

How do I use predefined themes in the theme builder when using CDNs?

Background

  • AG-Grid docs specify that it is acceptable to use a CDN for ag-grid-community.
  • AG-Grid 33+ errors when using < div class="ag-theme-balham" and recommends using the Theme API.
  • AG-Grid does not find themeBalham for gridOptions = {theme: <theme>} from the any CDNs that I tried:
<!-- AG-Grid + Styles -->
<script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>
<link  href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-grid.min.css" rel="stylesheet">
<link  href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-balham.min.css" rel="stylesheet">

Getting error in updating a document in mongodb using mongoose as ODM and nextjs in frontend [closed]

import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import underline from "../Image/underline.png"
import Link from "next/link"
import { useUser } from '@clerk/clerk-react'
import { ClerkProvider } from '@clerk/nextjs'
import { Github } from 'lucide-react'
import DialogViewer from "../Components/Dialog"
import { FaTrashAlt } from "react-icons/fa";
import { MdEdit } from "react-icons/md";

const FormDisplay = () => {
    const { isLoaded, user } = useUser()
    console.log(user)
    const [formdata, setFormdata] = useState({
        name_project: "",
        desc_project: "",
        url_project: "",
        name_comp: "",
        date_comp: "",
        url_comp: "",
        image_url: "",
        website_url: ""
    })
    let name, value;
    const handleInput = (e) => {
        name = e.target.name;
        value = e.target.value;
        setFormdata({ ...formdata, [name]: value })
    }

    const submit = async (e) => {
        e.preventDefault()
        const { name_project, desc_project, url_project, name_comp, date_comp, url_comp, image_url, website_url } = formdata
        const formData = {
            "name_project": name_project,
            "desc_project": desc_project,
            "url_project": url_project,
            "prizes": [
                {
                    "name_comp": name_comp,
                    "date_comp": date_comp,
                    "url_comp": url_comp
                }
            ],
            "image_url": image_url,
            "website_url": website_url,
            "clerkID": user.id
        }

        const response = await fetch("/api/addProject", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(formData)
        })

        const result = await response.json()
        console.log(result)
        if (result.success === true) {
            window.location.reload()
        }

    }
    return (
        <div className='w-auto pl-5'>
            <form action="">
                <br />
                <div className='flex gap-2 text-lg font-bold text-black '><p className='w-56 text-left pl-5'>Title:</p> <input type="text" name="name_project" id="name_project" onChange={handleInput} placeholder='Enter Title...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Description:</p> <textarea name="desc_project" id="desc_project" onChange={handleInput} placeholder='Enter Description...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Project URL:</p> <input type="text" name="url_project" id="url_project" onChange={handleInput} placeholder='Enter Project URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Image URL:</p> <input type="text" name="image_url" id="image_url" onChange={handleInput} placeholder='Enter Image URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Website URL:</p> <input type="text" name="website_url" id="website_url" onChange={handleInput} placeholder='Enter Website URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Name of Competition:</p> <input type="text" name="name_comp" id="name_comp" onChange={handleInput} placeholder='Enter Name of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Date of Competition:</p> <input type="text" name="date_comp" id="name_comp" onChange={handleInput} placeholder='Enter Date of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>URL of Competition:</p> <input type="text" name="url_comp" id="url_comp" onChange={handleInput} placeholder='Enter URL of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>

                <button className='bg-black text-white font-bold px-4 py-2 rounded-md mt-8' onClick={submit}>Submit</button>
            </form>
        </div>
    )
}

const Page = () => {
    const [projectData, setprojectData] = useState(null)
    const [runned, setRunned] = useState(false)
    const { isLoaded, user } = useUser()
    const [selectedProjectId, setSelectedProjectId] = useState(null);

    const getProjectData = async () => {
        if (!runned) {
            try {
                const response = await fetch("/api/getProject");
                const data = await response.json();
                setprojectData(data.data);
                // console.log("Fetched Data:", data);
                setRunned(true);
            } catch (error) {
                console.error("Cannot fetch data: ", error);
            }
        }
    };
    const deleteData = async (item) => {
        const _id = item.currentTarget.id
        console.log(_id)
        const confirmed = window.confirm("Are you sure you want to delete this project?")
        if (confirmed == true) {
            try {
                const response = await fetch("/api/deleteProject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ _id: _id })
                })
                const data = await response.json()
                console.log(data)
                if (data.success === true) {
                    window.location.reload()
                }
            } catch (error) {
                console.log("Cannot delete the project: ", error)
            }
        }
    }

    useEffect(() => {
        getProjectData();
    }, []);

    const Edit_FormDisplay = (item) => {
        const [data, setData] = useState()

        const [formdata, setFormdata] = useState({
            name_project: "",
            desc_project: "",
            url_project: "",
            name_comp: "",
            date_comp: "",
            url_comp: "",
            image_url: "",
            website_url: ""
        })
        useEffect(() => {
            const fetchOneProjectData = async () => {
                const _id = item.currentTarget.id
                console.log(_id)
                try {
                    const response = await fetch("/api/getOneProject", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ _id: _id })
                    })
                    const result = await response.json()
                    console.log(result)
                    setData(result.data)
                } catch (error) {
                    console.log("Cannot delete the project: ", error)
                }
            }

            fetchOneProjectData()
        }, [item])

        useEffect(() => {
            if (data) {
                setFormdata({
                    name_project: data.name_project || "",
                    desc_project: data.desc_project || "",
                    url_project: data.url_project || "",
                    name_comp: data.prizes?.[0]?.name_comp || "",
                    date_comp: data.prizes?.[0]?.date_comp || "",
                    url_comp: data.prizes?.[0]?.url_comp || "",
                    image_url: data.image_url || "",
                    website_url: data.website_url || ""
                });
            }
        }, [data]);
        const handleInput = (e) => {
            const { name, value } = e.target;
            setFormdata({ ...formdata, [name]: value });
        };

        const submit = async (e) => {
            e.preventDefault();
            const { name_project, desc_project, url_project, name_comp, date_comp, url_comp, image_url, website_url } = formdata;
            const formData = {
                name_project,
                desc_project,
                url_project,
                prizes: [
                    {
                        name_comp,
                        date_comp,
                        url_comp
                    }
                ],
                image_url,
                website_url,
            };

            try {
                const response = await fetch("/api/editProject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(formData)
                });
                const result = await response.json();
                console.log(result);
                if (result.success) {
                    window.location.reload();
                }
            } catch (error) {
                console.log("Error editing project:", error);
            }

        }
        return (
            <div className='w-auto pl-5'>
                <form action="">
                    <br />
                    <div className='flex gap-2 text-lg font-bold text-black '><p className='w-56 text-left pl-5'>Title:</p> <input type="text" name="name_project" id="name_project" onChange={handleInput} placeholder='Enter Title...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Description:</p> <textarea name="desc_project" id="desc_project" onChange={handleInput} placeholder='Enter Description...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Project URL:</p> <input type="text" name="url_project" id="url_project" onChange={handleInput} placeholder='Enter Project URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Image URL:</p> <input type="text" name="image_url" id="image_url" onChange={handleInput} placeholder='Enter Image URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Website URL:</p> <input type="text" name="website_url" id="website_url" onChange={handleInput} placeholder='Enter Website URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Name of Competition:</p> <input type="text" name="name_comp" id="name_comp" onChange={handleInput} placeholder='Enter Name of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Date of Competition:</p> <input type="text" name="date_comp" id="name_comp" onChange={handleInput} placeholder='Enter Date of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>URL of Competition:</p> <input type="text" name="url_comp" id="url_comp" onChange={handleInput} placeholder='Enter URL of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>

                    <button className='bg-black text-white font-bold px-4 py-2 rounded-md mt-8' onClick={submit}>Submit</button>
                </form>
            </div>
        )
    }


    return (
        <div className='bg-black sm:h-auto h-auto w-auto pt-16 text-white border-b-2 border-gray-600 scale-100 '>
            <h1 className='cedarville-cursive-regular text-4xl font-extrabold tracking-wide text-center mt-5 mb-14'>My Projects</h1>
            <div className='w-auto text-right mr-8'>
                {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ? <DialogViewer trigger_name={"+ Add New Project"} title={"Add a New Project"} description={"Fill the following fields to create/add a new project"} formElement={<FormDisplay />} /> : ""}
            </div>
            <Image src={underline} width={470} height={50} alt='underline' className='brightness-[100] absolute top-[6.7rem] left-[32rem] scale-75'></Image>

            {projectData === null ? (<div> Loading.... </div>) :

                (Array.isArray(projectData) && projectData.map((data) => {
                    return (
                        <div className='flex bg-gray-600 bg-opacity-50 m-3 rounded-lg h-96 scale-[98%] hover:scale-100 transition-all h-auto' key={data.name_project}>
                            <div className='w-[50%] p-7'>
                                <div className="relative w-[500px] h-[300px]" style={{ backgroundImage: `url(${data.image_url})`, backgroundSize: "contain", backgroundRepeat: "no-repeat", backgroundPosition: "center" }}>
                                    {/* <Image
                                    src={data.image_url}
                                    fill  // ✅ Makes the image fill the container
                                    className="rounded-lg object-cover"
                                    alt="card-image"
                                /> */}
                                </div>
                            </div>
                            <div className='w-[70%] p-7'>
                                <div className="w-[100%] text-right flex gap-3 justify-end ">
                                    {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ?
                                        <button className='text-red-500 bg-black w-8 h-8 text-center rounded-md pl-2' id={data._id} onClick={deleteData}><FaTrashAlt /></button>
                                        : ""}
                                    {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ? <button
                                        onClick={Edit_FormDisplay}
                                        id={data._id}
                                        className="bg-black text-green-500 h-8 w-auto font-bold rounded-lg px-2"
                                    ><DialogViewer trigger_name={<MdEdit />} title={"Edit an existing Project"} description={"Fill the following fields to edit a new project"} formElement={<Edit_FormDisplay />} /></button> : ""}
                                </div>
                                <div className='flex mb-7'>
                                    <div className='w-[65%] border-r-2 border-r-white mr-3'>
                                        <h2 className='text-white text-3xl font-extrabold tracking-wider mb-5 border-b-2 border-r-white mr-3 w-40'>{data.name_project}</h2>
                                        <p>{data.desc_project}</p>
                                    </div>
                                    <div>
                                        <h3 className='text-red-400 text-xl font-extrabold tracking-wide mb-5 border-b-2 border-b-white mr-3 w-20'>Prizes</h3>
                                        <p className=''>
                                            {Array.isArray(data.prizes) && data.prizes.map((data) => {
                                                console.log(data)
                                                return (
                                                    <>
                                                        <div className='flex' key={data.name_comp}><p>Name: &nbsp;</p><p className='cursor-pointer text-blue-600' >{data.name_comp}</p></div>
                                                        <p className='font-bold'>Participated in: {data.date_comp}</p>
                                                    </>
                                                )
                                            })}
                                        </p>
                                    </div>
                                </div>
                                <Link href={data.url_project} target='_blank'><button className='bg-green-500 text-black h-9 w-44 font-bold rounded-lg'><div className='flex'><Github className="h-5 w-5 pt-1 ml-3" /> &nbsp;&nbsp;View On Github</div></button></Link>&nbsp;&nbsp;
                                <Link href={data.website_url} target='_blank'><button className='bg-green-500 text-black h-9 w-32 font-bold rounded-lg'>Visit Website</button></Link>
                            </div>
                        </div>
                    )
                }))}
        </div>

    )
}



export default Page

This is the Dialog Viewer

import React from 'react'
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "../../components/components/ui/dialog"

const DialogViewer = ({ trigger_name, title, description, formElement }) => {
    return (
        <div>
            <Dialog className="text-black w-96">
                {trigger_name === "+ Add New Project"
                    ? (
                        <DialogTrigger className='bg-green-500 text-black h-9 w-auto font-bold rounded-lg px-2'>
                            {trigger_name}
                        </DialogTrigger>
                    )
                    : (
                        <div className="bg-black text-green-500 h-8 w-auto font-bold rounded-lg px-2">
                            <DialogTrigger>
                                {trigger_name}
                            </DialogTrigger>
                        </div>
                    )
                }
                <DialogContent className='text-black'>
                    <DialogHeader>
                        <DialogTitle className='text-black text-2xl font-extrabold text-center'>{title}</DialogTitle>
                        <DialogDescription className='text-lg'>
                            <p className='text-center'>{description}</p>
                            {formElement}
                        </DialogDescription>
                    </DialogHeader>
                </DialogContent>
            </Dialog>
        </div>
    )
}

export default DialogViewer

I have been trying to implement a page where I can display all the projects from the MongoDB database and perform all crud operations. The create, read, and delete functions are working fine. But when it comes to the edit part it is becoming a bit complex.

I am also getting this error: –
This error is according to me related to the function EditFormDisplay which is being called by a button. What can be an alternate method for this?

Error message: –
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.

For Your Info Dialog Viewer is taken from Schad cn UI which I made a separate component and its details are the props that I can pass from any component according to my need where I need to use it.

Please help me solve the problem in the above image

HTML Table Filtering via JavaScript Results in Disappearance of Sub-Tables

Using the following JavaScript, I am successfully filtering a table; however, sub-tables within each row are disappearing.

function filter_country_table_country_name_or_code() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("country_name_or_code_input");
  filter = input.value.toUpperCase();
  table = document.getElementById("country_table");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

function clear_country_table_country_name_or_code_field() {
    document.getElementById('country_name_or_code_input').value = "";
    filter_country_table_country_name_or_code()
}
<table id="country_table">
  <tr>
    Main Table Content Row 1
    <table>
      <tr>
        <td>
          Sub-Table Content Row 1
        </td>
      </tr>
    </table>
  </tr>
  <tr>
    Main Table Content Row 2
    <table>
      <tr>
        <td>
          Sub-Table Content Row 2
        </td>
      </tr>
    </table>
  </tr>
</table>

What could be causing this and what needs to change in my JavaScript?

Thank you.

How can I force an Infinity number to be a string in JavaScript, when I cannot control how I receive the input?

We receive data from a client. They pass it as XML which we use an automation platform (make.com) to translate.

We do not know the data coming in, we use a JavaScript function to process data.

One piece of data is represented as an Infinite number. We cannot convert it to String but we need to. Sample code below of the struggle.

function ____(val){
    return ``+val;
}
console.log(____(23E1028))

We need this function to return the string value, but we cannot control the data being passed to the function.

Some attempts:

23E1028
Infinity
String(23E1028)
'Infinity'
''+23E1028
'Infinity'
23E1028.charAt(0);
VM193:1 Uncaught TypeError: Infinity.charAt is not a function
23E1028
Infinity
String(23E1028)
'Infinity'
''+23E1028
'Infinity'
23E1028.charAt(0);
VM193:1 Uncaught TypeError: Infinity.charAt is not a function
function ____(val){
  return ``+val;
}
console.log(____(23E1028))

Is this a good use case for composition via higher-order functions?

I have a JavaScript project I’m working on and am wondering if I should switch from a long list of switches and if/then statements to a more compositional approach as I contemplate adding in a new, relatively large, feature.

In short, my program takes a large JSON file and does 2 recursive runs on it. The first run gathers information needed for the second run and does some structural edits, and the second performs performs a variety of straightforward html and formatting conversions to markdown.

The incoming JSON is pretty ubiquitous in the type and quantity of properties they have (around 4-6 properties). The main conversion loop in question here, will per JSON node, do the following:

  1. Pass the node to about 5 different functions that will always run on every node (linkify, turndown conversion, some other formatting conversions, etc)
  2. Based on the structure and type of the node, (about 15-20 options available), perform specific tasks that are exclusive to each other (this is done in a switch statement).
  3. The loop then will write the output to a map which later writes the content to markdown pages.

Another important note is that I have about 15 configuration options that are set once and performed uniformly across the entire JSON conversion process.

This setup works great so far. But here’s the kicker, the last main feature I need to implement is support for embedded script statements (found in the preconversion source JSON) that can:

  1. turn on/off configuration options on the fly
  2. treat certain nodes as a different type
  3. turn on/off certain conversions on each node
  4. perform certain text search/replacement
  5. Lots of other actions

And each of these actions can be performed:

  1. On the current node, or children only, or recursively down to all grandchildren
  2. Lots of other action parameters…

I needed a list-like entity anyway to pass down to each recursive call to keep track of what the action script wanted, so I was thinking maybe that’s the way to go for all the functionality?

Abstractly, what I have now is not an explosion of the kinds of actions that can be performed, because that feature set is pretty much all implemented, but instead an explosion of the combinations of actions that can be implemented per node.

I was thinking that rather than just a carefully ordered list of imperative if/then and switch statements, I would just re-work all the functionality into a set of discrete functions that can be composed, per node, based on the final result of all the configuration options, the action script tweaks, the structure of the nodes, etc. I would imagine that the final result would be a stack of objects that, containing relevant info and methods, could just be executed in order on the current node until satisfied.

Does this sound like a good use of composition via factory functions here?