class files structure in js

Hi folks.

I was really good in JS, but … 20 years ago. 😉
Then I learned PHP, then C++, a lil-bit Java and recently C#.NET.

Due to some upcoming private web projects, I’m trying to find back in JavaScript again. I looked at the prototypes and also how to create classes. The lack of type safety bothers me a bit, reminds me of the PHP mixed var types. Also, the annoying typing of “this.*” for each member/field of a class is exhausting. But well, that’s the way it is.

However, my main concern describes the clear structuring of an entire collection of classes, e.g. for larger model or MVVM structures.

I quickly took a look at the latest Vue.JS documentation, the getters and setters for the MVVM object are also generally nice.

Nevertheless, I would prefer a structure like the one known from C#.NET. So a separate file for each class. The question is how do I link all these files and how can I make sure that classes used within other classes (as member/field or via inheritance (extends, :)) are already available according to the order. So previously listed in a merge code.

Are there already libraries or is it somehow very easy to do it yourself? Or does anyone know of some more elegant ways?

It is important to me that with more than 250 classes, subclasses and nested combinations, I can find the classes I am looking for quickly and clearly and update them as cleanly and encapsulated as possible.

But I hope you understand, what I want to have. I’m looking for a way to combine/merge and minify a long list of class files into one *.js file, like a build compiler in C# creates an *.exe file. But in a valid order.

Or am I thinking too much in C#.NET here?
Please don’t see this post as a code question.
I enjoy in a discussion of techniques, libraries and would appreciate some help using these patterns or ideas.


Just for info: My first web project should be a small blog/community for “movies & games” with techniques like:

  • MVVM, binder/observers, shaddow DOM
  • speed ups (lazy load, shaddow DOM, preloads)
  • locally data storages (indexedDB)
  • offline page/js/css with serviceWorker
  • SPA and url manipulation (history.pushState or “/#/…”)

JavaScript: How to sum the values greater than 16 in a list of editable numbers

I’m a new at JavaScript and I’m trying to do the following:

I’m making a fillable .pdf file. The user enters numbers in 7 different fields and gets an output in an 8th field. I want to take the sum of the values greater than 16.

For example: The user enters the following numbers in each field (16, 16, 16, 16, 16, 16, 16). The program sees that no value is above 16, so the output appears in an 8th field as 0.

Now the user enters (17, 17, 16, 16, 16, 16, 16), so the output is 2.

I’m not sure if this requires an array or not? Any thoughts? Thank you in advance.

function to generate cards

How do I write a function in vanilla javascript for a Memory Game to generate:

32 cards in total with shapes on them
each shape  in 4 colors
2 cards of each color

color               shapes
yellow     square, triangle, round, oval
green      square, triangle, round, oval
blue       square, triangle, round, oval
red        square, triangle, round, oval

How to pass props in getStaticProps to a component in Next.js

Overview

I am trying to pass on object of data that contains strings and objects to my component

The Problem

When I check the Next.js documentation to pass props, I try to send it in the key value pair format. When I try to use any of my props in my component, they are undefined. Am I de-structuring wrong?

My attempts

This is what I am currently working with. I fetch some data, get the first object in an array of objects and de-structure only the keys I want. Then I set the keys to a park object.

export async function getStaticProps({params}) {
  const URL = 'https://developer.nps.gov/api/v1/'

  // Call API Data for /PARK
  const res = await fetch(
    `${URL}parks?parkCode=${params?.parkCode}&limit=465&api_key=${process.env.API_KEY}`,
    {
      method: 'GET',
      headers: {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': '*',
      },
    }
  )

  const parkData = await res.json()

  if (!parkData) {
    return {notFound: true}
  }

  const park = parkData?.data[0]

//  The park object looks like this:
{
  name: 'A name',
  fullName: 'John Doe',
  parkCode: 'abcd',
  description: 'lorem ipsum',
  designation: 'park',
  imags: [
    {
      url: 'http://...',
      title: 'img1',
    },
    {
      url: 'http://...',
      title: 'img1',
    },
  ],
}


  const {name, description, parkCode, designation, images, fullName} = park

  return {
    props: {
      park: {name, fullName, description, parkCode, designation, images},
    },
    revalidate: 1,
  }
}

In my component, this is how I try to consume it, but I get undefined errors.

export default function Park({park}) {
  console.log(park) // undefined
}

React.js Uncaught SyntaxError: Unexpected token ‘:’

my first react-app

error in dev-console:

VM4091:1 Uncaught SyntaxError: Unexpected token ':'
        at a (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:254:358)
        at a.c._inlineJS (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:255:1551)
        at b (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:255:1002)
        at xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:3616
        at Array.forEach (<anonymous>)
        at j (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:3596)
        at Object.appendContent (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:2032)
        at Object.setContent (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:1880)
        at b.<anonymous> (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:39:2329)
        at qg (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:58304)
        at Pj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:118010)
        at Oj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:117570)
        at Nj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:117105)
        at Lk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:127623)
        at Kk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:126938)
        at xk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:123399)
        at Sf (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:52366)
        at qk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:120184)
        at Object.enqueueSetState (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:58710)
        at b.a.setState (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:58:1753)
        at 9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:39:2237
        at AsyncRequest._dispatchResponse (x9ZrO_yAkJs.js?_nc_x=JMPQFHF0fM0:16:6351)
        at Object.applyWithGuard (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:9982)
        at AsyncRequest.c (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:10686)
        at x9ZrO_yAkJs.js?_nc_x=JMPQFHF0fM0:15:84
        at e (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:322:291)
        at Object.applyWithGuard (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:9982)
        at d (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:296:2252)

I need help so the errors disappear from developer toolbar console tab.
Thank you,

The error exist only when i use:

<FacebookProvider appId="someAppId">
    <Page
      href="http://www.facebook.com/somePage"
      tabs="timeline"
    />
</FacebookProvider>

package.json:

{
      "name": "kpw",
      "version": "0.1.0",
      "private": true,
      "typings": "./global.d.ts",
      "babel": {
          "presets": [
              "@babel/preset-env",
              "@babel/preset-react"
          ]
      },
      "dependencies": {
          "@babel/cli": "^7.16.8",
          "@babel/core": "^7.16.10",
          "@babel/preset-env": "^7.16.11",
          "@babel/preset-react": "^7.16.7",
          "@fortawesome/fontawesome-svg-core": "^1.2.36",
          "@fortawesome/free-brands-svg-icons": "^5.15.4",
          "@fortawesome/free-regular-svg-icons": "^5.15.4",
          "@fortawesome/free-solid-svg-icons": "^5.15.4",
          "@fortawesome/react-fontawesome": "^0.1.16",
          "@testing-library/jest-dom": "^5.16.1",
          "@testing-library/react": "^12.1.2",
          "@testing-library/user-event": "^13.5.0",
          "@types/react-router-dom": "^5.3.3",
          "bootstrap": "^5.1.3",
          "eslint-import-resolver-typescript": "^2.5.0",
          "prop-types": "^15.8.1",
          "react": "^17.0.2",
          "react-bootstrap": "^2.1.0",
          "react-dom": "^17.0.2",
          "react-facebook": "^8.1.4",
          "react-router": "^6.2.1",
          "react-router-dom": "^6.2.1",
          "react-scripts": "5.0.0",
          "web-vitals": "^2.1.2"
      },
      "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject"
      },
      "eslintConfig": {
          "extends": [
              "react-app",
              "react-app/jest"
          ]
      },
      "browserslist": {
          "production": [
              ">0.2%",
              "not dead",
              "not op_mini all"
          ],
          "development": [
              "last 1 chrome version",
              "last 1 firefox version",
              "last 1 safari version"
          ]
      },
      "devDependencies": {
          "@types/react": "^17.0.38",
          "eslint": "^8.6.0",
          "eslint-config-prettier": "^8.3.0",
          "eslint-plugin-prettier": "^4.0.0",
          "eslint-plugin-react": "^7.28.0",
          "prettier": "^2.5.1"
      }
}

eslint.js:

{
“env”: {
“browser”: true,
“es6”: true,
“es2021”: true,
“jest”: true,
“node”: true
},
“extends”: [
“eslint:recommended”,
“plugin:react/recommended”,
“plugin:prettier/recommended”
],
“parserOptions”: {
“ecmaFeatures”: {
“jsx”: true
},
“ecmaVersion”: 13,
“sourceType”: “module”
},
“plugins”: [
“react”
],
“settings”: {
“import/resolver”: {
“typescript”: {}
}
},
“rules”: {
“react/react-in-jsx-scope”: “off”,
“react/jsx-filename-extension”: [
1,
{
“extensions”: [
“.js”,
“.jsx”
]
}
],
“react/forbid-prop-type”: [
0,
{
“forbid”: [
“any”
]
}
],
“react/self-closing-comp”: [
“error”,
{
“component”: true,
“html”: true
}
],
“prettier/prettier”: [
“error”,
{
“singleQuote”: true,
“parser”: “flow”
}
]
}
}

Why aren’t Vue prop changes triggering reactivity in my bundled component?

I’ve been troubleshooting this issue for a while now and I’m running out of ideas. I hope some fresh eyes can give me a better perspective.

In short: I have several computed properties in a component that are not reacting to changes in props only after bundling. Before bundling, the computed properties work exactly as expected.

Here’s the relevant bits of code. For context, this is part of a paginated data table component.

setup(props) {
    props = reactive(props);
   
    const isNextDisabled = computed(() => props.index + props.pageSize >= props.totalSize

    const rangeUpperBound = computed(() => {
        let upperBound = props.index + props.pageSize;
        if (upperBound > props.totalSize) {
            upperBound = props.totalSize;
        }
        return upperBound;
    });

    return {
        isNextDisabled,
        upperBound,
    }
}

I’m using Storybook.js to develop this component as part of a library. I’m also trying to simulate async data fetching, so my props are initially null values and then I have a setTimeout function that loads some data from a file after 1.5 seconds. In other words, my props are definitely being updated and I expect my computed properties to be evaluated twice (once at first render, again when the props they depend on are updated).

When I’m developing the components with the vanilla npm run storybook command everything works as expected. All the computed properties are updated properly once the timeout finishes, and the component renders correctly. I hit snags when I bundle my components.

I’m using Vue CLI’s default configuration to bundle things, my command is:

vue-cli-service build --target lib --name copper-vue src/index.js

Here is that src/index.js file:

export { default as DataTable } from "./components/DataTable/DataTable";

Here’s my problem: When I use the component from the bundled file none of the computed properties in my component are updated when the props are updated after the setTimeout. I’ve verified with logging statements and a debugger that the computed properties are only evaluated once when the component first renders, and they seem to completely ignore the fact that the props they depend on have updated. I’ve also verified this happens with a watchEffect call I added during my testing.

I’ve been testing this by importing the bundled component, rather than the component from my .vue file, in my Storybook story like so:

// Shortcut story in question:

<template>
  <span>This story waits 1.5 seconds before it loads any data, as a rudimentary way to simulate async data fetching.</span>
  <data-table
    :data="dataSubset"
    :columns="columns"
    @editRow="handleEditRow"
    paginate
    :index="index"
    :page-size="pageSize"
    :total-size="totalSize"
    @change-page="getNewPage"
    @change-page-size="changePageSize"
  />
</template>

<script>
// This is the import to use the component from the SFC
// import DataTable  from "./DataTable.vue";

// Here's how I import the component from the bundled file which causes issues
import { DataTable } from "../../../dist/copper-vue.common";

...
</script>

Other relevant details:

  • This bug happens in both Chrome and Firefox
  • I’m using Vue 3.2.8, Storybook 6.3.12
  • Running/bundling on a 2020 M1 Macbook pro

Things I might try next:

  • Walking back some Vue versions to see if 3.1 works, 3.0 works, etc

Is there something about the reactive APIs that I’m doing incorrectly here? I’m completely baffled why things work as expected when running in a “dev” mode and not when bundled using Vue CLI. Any tips are appreciated.

jquery post – how to send code snippets to mysql database

bstory is a contenteditable div and typing inside – it sends the content to remote database
everything works except – if the content is – for example – session_start – I’m getting error 403 in console
on php side I’m using PDO
inside this table I want to store code snippets from various programming languages, but obviously there is a flag – even if PDO is used

how to do this, pls

$('#bstory').on('input', function(){
    let id = get_id();
    let story = $(this).text().trim();
    $.post('pro.php', {fn: 'bstory_input', args:[id, story]}, function(data){
        console.log(data);  // error
    });
});

php

function bstory_input($id, $story){
    global $db;
    $sq = "update nts set story = :astory where id = :aid";
    $st = $db->prepare($sq);
    $st->execute([
        ":astory" => $story,
        ":aid" => $id
    ]);
}

Why do i have the error WebSocket connection failed – socket.io

I’m working with socket.io in React JS (client) and Node JS (server), and when i deployed the apps i got WebSocket connection to ‘wss://***.com:57284/ws’ failed.

enter image description here

Running locally it dont happend and i’d like to know why and how to solve it.

This is the server code

const {Server} = require("socket.io");


const port = process.env.PORT || 5000
// io.listen(port);
console.log("Server listening on " + port)
const io = new Server(port, {
    cors: {
        origin: "https://***.com",
        methods: ["GET", "POST"]
    },
    path: "/api/",
});
io.on("connection", (socket) => {
***all socket logic***
});


and the client

  const [socket, setSocket] = useState(null)
  useEffect(() => {
    const newSocket = io("https://***.com", {transports: ['websocket'], path: "/api/"})
    setSocket(newSocket)
    return () => newSocket.close()
  }, [setSocket])

JS simple christmas tree on one loop

I’m trying to make one loop christmas tree using string.repeat method.

  let Height = 6;
  let Star = "*";

  for (let i = 0; i < Height; i++) {
    for (let j = 0; j <= i; j++) {
      document.write(Star);
    }
    document.write("<br>");
  }

I’ve created it on 2 loops, but don’t know how to do it on a single one. Thank you for help.

CastError: Cast to ObjectId failed for value “XXXXXXXXXX” (type string) at path “_id” for model “User” for passport-linkedin-oauth2

Getting the above error when trying to authenticate a new user using LinkedIn’s oAuth 2.0. It looks like I’m getting passed a 10 digit ObjectId instead of a 12 or 24 character id…

passport.use(new LinkedInStrategy({
  clientID: process.env.LI_ID,
  clientSecret: process.env.LI_SECRET,
  callbackURL: "http://localhost:3000/auth/linkedin/think-it",
  scope: ['r_emailaddress', 'r_liteprofile'],
  state: true
}, function(accessToken, refreshToken, profile, done) {
  // asynchronous verification, for effect...
  process.nextTick(function () {
    // To keep the example simple, the user's LinkedIn profile is returned to
    // represent the logged-in user. In a typical application, you would want
    // to associate the LinkedIn account with a user record in your database,
    // and return that user instead.
    return done(null, profile);
  });
}));

I’m getting hung up at:

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

How does hidden classes really avoid dynamic lookups?

So we have all heard that v8 uses the thing called hidden classes where when many objects have the same shape, they just store a pointer to the shape struct which stores fixed offsets. I have heard this a million time, and I very much get how this reduces memory usage by A LOT (not having to store a map for each one is amazing) and potentially because of that a bit faster performance.

However I still don’t understand how it avoids dynamic lookup. The only thing I have heard is storing a cache between a string (field name) and a fixed offset, and checking it every time, but if there’s a cache miss (which is likely to happen) there will still be a dyanmic lookup.

Everyone says that this is almost as fast as C++ field access (which are just a mov instruction usually), however this 1 field access cache isn’t even close.

Look at the following function:

function getx(o)
{
    return o.x;
}

How will v8 make the access of the x field so fast and avoid dynamic lookup?

Calculate price from width and height

The question is divided into 2 parts.

1. How to structure the data in the json array

2. How to calculate the price from the json array

I need to store the price data inline in HTML as JSON, as AJAX requests to the server are too slow/heavy.

The data are stored as serialized strings in a database. This is added to the database from CSV file uploads. The CSV files looks like below.

      50    100    150    200    250
20    70     90    110    130    150
30    90    110    130    150    170
40    110   130    150    170    190
50    130   150    170    190    210
60    150   170    190    210    230

If you enter 100 in width and 40 in height, the price should be 130.

If you enter 170 in width and 52 in height the price should be 210.

If column or row is not found, it should round up to next column or row.

  1. What is the best way to store this as JSON inline, if you need to calculate the price based on width and heigth?

  2. How would you calculate the price, based on user input width and height?

I am not looking for specific code, just suggestions on the JSON structure and how to calculate from this.

Incrementing DynamoDB value using AWS SDK v3

I’m attempting to migrate my v2 Lambdas to v3, and I’m having some trouble incrementing a value. Here’s my v2 method:

  const params = {
    TableName: process.env.USER_TABLE_NAME!,
    Key: { UID },
    UpdateExpression: 'SET #numRatings = #numRatings + :increment',
    ExpressionAttributeNames: {
      '#numRatings': 'numRatings'
    },
    ExpressionAttributeValues: {
      ':increment': 1
    },
    ReturnValues: 'ALL_NEW'
  };

  return await DB.update(params).promise();

v3 method:

  const params = {
    TableName: process.env.USER_TABLE_NAME!,
    Key: {
      UID
    },
    UpdateExpression: 'set numRatings = numRatings + :increment',
    ExpressionAttributeValues: {
      ':increment': 1
    },
    ReturnValues: 'ALL_NEW'
  } as unknown as UpdateItemCommandInput;

  try {
    const response = await dbClient.send(new UpdateItemCommand(params));
    console.log('response', response);
  } catch (error) {
    console.error('error', error);
  }

I’m using TypeScript and VS Code gives this error:

Types of property 'Key' are incompatible.
    Type '{ UID: string; }' is not comparable to type '{ [key: string]: AttributeValue; }'.
      Property 'UID' is incompatible with index signature.
        Type 'string' is not comparable to type 'AttributeValue'

CloudWatch gives this unhelpful error:

Cannot read property ‘0’ of undefined

I’m really confused as, as far as I can tell I have followed the documentation properly, their equivalent of “params” is defined as so:

export const params = {
  TableName: "TABLE_NAME",
  Key: {
    primaryKey: "VALUE_1", // For example, 'Season': 2.
    sortKey: "VALUE_2", // For example,  'Episode': 1; (only required if table has sort key).
  },
  // Define expressions for the new or updated attributes
  UpdateExpression: "set ATTRIBUTE_NAME_1 = :t, ATTRIBUTE_NAME_2 = :s", // For example, "'set Title = :t, Subtitle = :s'"
  ExpressionAttributeValues: {
    ":t": "NEW_ATTRIBUTE_VALUE_1", // For example ':t' : 'NEW_TITLE'
    ":s": "NEW_ATTRIBUTE_VALUE_2", // For example ':s' : 'NEW_SUBTITLE'
  },
  ReturnValues: "ALL_NEW"
};

My apologies if that’s too many code examples but I wanted to be thorough. UID is a string. Thank you in advance for any help

Method not getting triggered on click React

I am trying to render a popup when a card is clicked. My problem is that I can’t get the showPopup function running on click of the card component.

//... all required imports 

class App extends Component {
  constructor() {
    super();

    this.state = {
      monsters: [],
      searchField: ''
    };
  }

  componentDidMount() {
    // Fetches monsters and updates the state (working fine)
  }

  showPopup = () => {
    console.log(2);
  };

  render() {
    const { monsters, searchField } = this.state;
    const filteredMonsters = monsters.filter(monster => monster.name.toLowerCase().includes(searchField.toLowerCase()));

    return (
      <div className="App">
        <CardList className="name" monsters={filteredMonsters} showPopup={e => this.showPopup(e)} />
      </div>
    );
  }
}

Following is the code for my CardList component

import React from 'react';
import { Card } from '../card/card.comp';
import './card-list.styles.css';

export const CardList = props => {
    return (
      <div className="card-list">
        {props.monsters.map(monster => (
          <Card key={monster.id} monster={monster} onClick={props.showPopup} />
        ))}
      </div>
    );
};

The onclick function above is not working as expected. Please help me find out the problem.