How to create a `Callable` object in JavaScript, without inheriting from `Function` and with no type errors?

As stated in this blog post and in this stack overflow post, it is possible to make an object callable as follows:

class Callable extends Function {
    constructor() {
        super();
        var closure = function (...args) { return closure._call(...args) }
        return Object.setPrototypeOf(closure, new.target.prototype)
    }

    _call(...args) {
        console.log(this, args)
    }
}

However, this causes problems with CSP (Content-Security-Policy), like when running in a Chrome extension. It is possible to remove the extends Function and super() calls, but this results in type errors. For my use-case, I unfortunately can’t ignore this. If there’s a way to override the type errors (e.g., using JSDoc), that could also work.

Any help will be greatly appreciated.

jQuery save button to local storage

Hi I am working on a project where I input text and want to save it to my local storage.
How do I do that? The issue is every time I try it, my current timer t code I have that works, stops working and I am back to square 1.

webscraping with javascript

need help gathering data from different time intervals. i want to gather the summary of the technical analysis from the 15 as well as the 30min timeframe with the amount of buy, neutral and sell and maybe put it in a nice, easy to read table.

picture of what im looking fore
Link to website: https://www.tradingview.com/symbols/SPX/technicals/?exchange=SP

i have done some very basic webscraping before but this very new for me, i would be very grateful for any help 🙂

How can I make the materialUI drawer scroll to bottom after a refresh? in React

I have a Material UI Drawer with lots of checkboxes and radio buttons for an advanced search page. Each and every checkbox or radio click mutates the API get request for a “on-the-fly” results without the need to click a submit button. My problem is that every time this happens, because there is a refresh happening, the drawer resets back top the top.

I have all of my radio buttons at at the bottom so if I could at least force those click events for the radio buttons to scroll my drawer to the bottom, that would make it look like it preserved the scroll position.

function scrollToBottom() {
    let height = document.getElementById('customAdvancedDrawer').clientHeight;
    
    const drawerEl = document.getElementById('customAdvancedDrawer').getScrollElement();
      
    drawerEl.scrollTop = height; //Is there such a thing as .scrollBottom?
}

I tried the function above but it doesn’t work and I’m getting an error Cannot read properties of undefined (reading 'getScrollElement'). I’m assuming that the drawer is not mounted when this fires?

I’m calling the function in the onChange event

<CustomRadioGroup 
    className="preventJumpToTop"
    radiodata={selectors.regions} 
    radiovalues={state.region} 
    defaultValue={state.region} 
    handleOnRadioChange={(value) =>  {
       setState({ ...state, region: value }); 
       scrollToBottom()
    }} 
    radiolabel="Region" />

Javascript groub Array by different properties

I would like to group a array of objects in JavaScript.

[
  { count: 6, month: 11, type: 'categoryA', year: 2022 },
  { count: 5, month: 12, type: 'categoryA', year: 2022 },
  { count: 10, month: 1, type: 'categoryA', year: 2023 },
  { count: 5, month: 1, type: 'categoryC', year: 2023 },
  { count: 26, month: 2, type: 'categoryA', year: 2023 },
  { count: 10, month: 2, type: 'categoryC', year: 2023 },
  { count: 2, month: 3, type: 'categoryA', year: 2023 },
  { count: 31, month: 3, type: 'categoryA', year: 2023 },
  { count: 8, month: 3, type: 'categoryB', year: 2023 },
  { count: 7, month: 4, type: 'categoryA', year: 2023 },
  { count: 4, month: 4, type: 'categoryB', year: 2023 }
]

I want to get the Count of categoryA and categoryC per month and year.

[
  { count: 6, month: 11, type: 'categoryA_and_CategoryC', year: 2022 },
  { count: 5, month: 12, type: 'categoryA_and_CategoryC', year: 2022 },
  { count: 15, month: 1, type: 'categoryA_and_CategoryC', year: 2023 },
  { count: 36, month: 2, type: 'categoryA_and_CategoryC', year: 2023 },
  { count: 2, month: 3, type: 'categoryA_and_CategoryC', year: 2023 },
  { count: 31, month: 3, type: 'categoryA_and_CategoryC', year: 2023 },
  { count: 8, month: 3, type: 'categoryB', year: 2023 },
  { count: 7, month: 4, type: 'categoryA_and_CategoryC', year: 2023 },
  { count: 4, month: 4, type: 'categoryB', year: 2023 }
]

I found no smart way to do the grouping and maybe someone has an idea to implement it in a elegant way.

Need assistance to fix console error saying ‘Uncaught (in promise)’

i’m trying to solve a problem in which i have to use a find() method and it’s giving me an error

import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstant';

const cartReducers = (state = { cartItems: [] }, action) => {
  switch (action.type) {
    case CART_ADD_ITEM:
      const item = action.payload;

      const existItem = state.cartItems.find((x) => x.product === item.product);

      if (existItem) {
        return {
          ...state,
          cartItems: state.cartItems.map((x) =>
            x.product === existItem.product ? item : x
          ),
        };
      } else {
        return { ...state, cartItems: [...state.cartItems, item] };
      }

    default:
      return state;
  }
};

export default cartReducers;

This is my cartReducer.js file and i get an error in this file, when switching to a case ‘CART_ADD_ITEM’

the error looks like this piece of code below

caught (in promise) TypeError: Cannot read properties of undefined (reading 'find')
at cartReducers (cartReducers.js:8:1)
at combination (redux.js:560:1)
at E (<anonymous>:1:33326)
at I (<anonymous>:1:33613)
at <anonymous>:1:37893
at Object.dispatch (redux.js:288:1)
at e (<anonymous>:1:38904)
at index.js:20:1
at dispatch (redux.js:691:1)
at cartAction.js:7:1

c

r.createRoot is not a function?

when i deploy personal project react js go up netlify! help me.thank!
my file index.js:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import { store } from "./redux/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
   </React.StrictMode>
);

reportWebVitals();

hope every one can help me !

Display partial response including styles

When I make a rest call in react, I get a style and html response as follows. Is not in String format.
How can I display this in React as a partial html fragment?

Bear in mind I can’t just use dangerouslySetInnerHTML.
That will take care of the html yes. But will not recognise the style.

// This won't capture styles.
const Partial = ({ html }) => {
    return (
      <span
        dangerouslySetInnerHTML={{
          __html: html.toString(),
        }}
      />
    );
  };
  
export default Partial;

There are hundreds of styles and hundreds of elements here. The following is just a sample.
Trying to achieve this without any additional libs.

This is the response, not in String format. Believe is text/html.

<style>
    .sample {
        margin: 0;
    }
    /* hundreds of other styles */
</style>
<style>
    .sample2 {
        padding: 0;
    }
    /* hundreds of other styles */
</style>
<!-- many other style tags -->
<div>
    test
    <div>another</div>
    /* hundreds of other elements */
</div>
<div>
    test
    <div>another</div>
    /* hundreds of other elements */
</div>

how to add labels to geojson layer in google maps

I have a polygon layer geojson that show the states of the US. I use this layer on a google maps (using the google maps js api).

I can get the polygons to display, but I want to set labels on each state. How do I add the labels to the state?

here’s my code:

map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: latitude, lng: longitude},
  zoom: 13
});

map.addListener("zoom_changed", () => {
    if (map.getZoom() < 8) {
        console.log(map.getZoom() + " Get States")
        map.data.forEach(function(feature) {
            map.data.remove(feature);
        });
        map.data.loadGeoJson(
            "data/states.json"
        );
    }
    else {
        console.log(map.getZoom() + " Get Counties")
        map.data.forEach(function(feature) {
            map.data.remove(feature);
        });
        map.data.loadGeoJson(
            "data/counties.json"
        );
    }
});

How can I update a nested object in JavaScript and Typescript?

I have a data object that I want to update the values inside, but it can be a value inside a nested object. But its exact location is not known.
I put it’s parents’ names inside each one. A form is created from this object and I need to be able to change the values inside the object by entering the values in the form.

obj['key2']['key3']['childern'][key4].value = 'anyting'

I don’t know how nested this object can be.

object sample:

 obj = {
   key1:{
           type='parent',
           name='parent1',
           ...
           childern:[
              key2:{
               type='any',
               value='',
               parents = ['key1']
            },
             key3:{
               type='parent',
               value='',
               parents = ['key1'],
           childern:[
              key4:{
               type='any',
               value='',
               parents = ['key1','key3']
            }]
            },

           ]


        }
}

aws-sdk v3 javascript, condition expression wont work for put command

I want to create putItem function, where it prevents overwriting previous item if ‘userId’ already existed. Upon searching, I figured that one can use condition expression in the params object before passing to putcommand from aws-sdk. But the problem is, it still update the item, even though the userId has existed. Need your help if anyone can review my code and tell me where I did wrong. Thank you.

import { PutCommand } from "@aws-sdk/lib-dynamodb";
import { ddbDocClient } from "./ddbDocClient.js";

const putItem = async (newItemObject) => {
    //check for userId
    const userId = {newItemObject};
    if(userId){
        console.log({userId});
        // Set the parameters.
        const params = {
        TableName: "portal-users",
        Item: newItemObject,
        ConditionExpression: "userId = :userIdVal",
        ExpressionAttributeValues: {
            ":userIdVal" : userId,
        }
        };
        try {
            const data = await ddbDocClient.send(new PutCommand(params));
            console.log("Success - item added or updated", data);
        } catch (err) {
            console.log("Error", err.stack);
        }
    } else {
        console.log('user id is undefined, please provide for new user id');
    }
};

const newUser = [
    {
        userId: 'user01',
        nameFirst: 'alison',
        nameLast: 'swift'
    }
]

newUser.map(x => putItem(x));

How to load assets via JSONP into Phaser

I am trying to load data (including images) via a JSONP feed into Phaser 3.60.0. I know how to load image asset normally as per my GameScene.js code below:

class GameScene extends Phaser.Scene {
  constructor() {
    super({ key: 'GameScene' });
  }

  preload() {
    this.load.image('oranges', './assets/Ambersweet_oranges.jpg');
  }

  create() {
    this.add.image(240, 320, 'oranges')
  }
}

The JSONP feed is located on a different server and is structured like this:

/**/ typeof handleItems === 'function' && handleItems([
{"offerWeek":"kw17","id":"1028377","name":"Bananen","price":"1.79","url":"https://www.rewe.de/angebote/nationale-angebote/#1028377","image":"https://upload.wikimedia.org/wikipedia/commons/5/5d/Pl%C3%A1tanos_de_Canarias.JPG"},
{"offerWeek":"kw17","id":"2670547","name":"Big City Pizza","price":"1.99","url":"https://www.rewe.de/angebote/nationale-angebote/#2670547","image":"https://upload.wikimedia.org/wikipedia/commons/a/a5/Pizza_20.jpg"},
{"offerWeek":"kw17","id":"3663221","name":"Die Thüringer Bratwurst","price":"4.59","url":"https://www.rewe.de/angebote/nationale-angebote/#3663221","image":"https://upload.wikimedia.org/wikipedia/commons/9/91/Bratwurst_on_the_grill.jpg"},
{"offerWeek":"kw17","id":"3919250","name":"Orangen","price":"2.99","url":"https://www.rewe.de/angebote/nationale-angebote/#3919250","image":"https://upload.wikimedia.org/wikipedia/commons/4/43/Ambersweet_oranges.jpg"}]
);

How do I access the product names and images and display them in Phaser? Also how do I wait for the request to finish before create() is called? All advice appreciated!

Create nice looking array object based on key value in a for loop

I’m having a little bit of trouble creating an object of a couple of fields, pushing them and creating a nice looking object:

// function to extract integer from key field...
function pad3(position) {
    return parseInt((position < 10 ? position.charAt(1) : position))
}

for (let field of formData) {
        key = field[0]
        val = field[1]
        position = pad3(key.substring(0,2)) // 00- becomes 0, 01- becomes 1 etc...

        let obj = []
        obj = {[key.substring(3,key.length)]: val}
        arr.push(obj)   
}

Console logging key and val within this loop during iteration looks like:

console.log(key) // 00-account_a
console.log(val) // 111
console.log(key) // 00-account_b
console.log(val) // 222

console.log(key) // 01-account_a
console.log(val) // 333
console.log(key) // 01-account_b
console.log(val) // 444

console.log(key) // 02-account_a
console.log(val) // 555
console.log(key) // 02-account_b
console.log(val) // 666

and so on …

I would like to create a nice looking Array object from this data but I’m struggling…
How do I create a nice looking array object based on the position variable?

Something Like:

Accounts [
[0] {   // <-- [0] based on "position" variable ...
    account_a: 111,
    account_b:222
},
[1] { 
    account_a: 333,
    account_b:444
},
[2] { 
    account_a: 555,
    account_b:666
},
]