Passing multiple params in react-router-dom like reactnavigation

Well, I’ll get to the point with this, and I have a problem passing parameters to the browsing history
For those with experience in reactnavication, you will know how easy it is to pass multiple parameters in the form of an object.

now the problem I have is that the following block

goToChat = (chat) =>
  const { params } = this.props.route;
  const post = params && params.post ? params.post : ""
  const anotherParam = params && params.anotherParams ? params.anotherParams : ""
  ...
  if (chat) {
    this.props.navigation.navigate(CHAT_ROUTE, { chat, param, anotherParam, ... })
  } else {
    ...
  }
}

I have to make it work in a history.push with React-router-dom,
but I haven’t found a way to do it
this is what i improvised

goToChat = (chat) =>
  const { params } = this.props.match;
  const post = params && params.post ? params.post : ""
  const anotherParam = params && params.anotherParams ? params.anotherParams : ""
  ...
  if (chat) {
    this.props.history.push(`${CHAT_ROUTE}/${chat}/, post, anotherParam, ... }`)
  } else {
    ...
  }
}

I’m not sure if I’m close to finding the solution with that attempt

Algorithm implementation to convert propositional formula into conjunctive normal form in JavaScript?

I saw How to convert a propositional formula to conjunctive normal form (CNF)? but it doesn’t go into implementation details. So I was lucky to find this which shows the types:

abstract class Formula { }
class Variable extends Formula { String varname; }
class AndFormula extends Formula { Formula p; Formula q; }  // conjunction
class OrFormula extends Formula { Formula p; Formula q; }  // disjunction
class NotFormula extends Formula { Formula p; } // negation
class ImpliesFormula extends Formula { Formula p; Formula q; } // if-then
class EquivFormula extends Formula { Formula p; Formula q; }
class XorFormula extends Formula { Formula p; Formula q; }

Then it has this helpful (start of a) function CONVERT:

CONVERT(φ):   // returns a CNF formula equivalent to φ

// Any syntactically valid propositional formula φ must fall into
// exactly one of the following 7 cases (that is, it is an instanceof
// one of the 7 subclasses of Formula).

If φ is a variable, then:
  return φ.
  // this is a CNF formula consisting of 1 clause that contains 1 literal

If φ has the form P ^ Q, then:
  CONVERT(P) must have the form P1 ^ P2 ^ ... ^ Pm, and
  CONVERT(Q) must have the form Q1 ^ Q2 ^ ... ^ Qn,
  where all the Pi and Qi are disjunctions of literals.
  So return P1 ^ P2 ^ ... ^ Pm ^ Q1 ^ Q2 ^ ... ^ Qn.

If φ has the form P v Q, then:
  CONVERT(P) must have the form P1 ^ P2 ^ ... ^ Pm, and
  CONVERT(Q) must have the form Q1 ^ Q2 ^ ... ^ Qn,
  where all the Pi and Qi are dijunctions of literals.
  So we need a CNF formula equivalent to
      (P1 ^ P2 ^ ... ^ Pm) v (Q1 ^ Q2 ^ ... ^ Qn).
  So return (P1 v Q1) ^ (P1 v Q2) ^ ... ^ (P1 v Qn)
          ^ (P2 v Q1) ^ (P2 v Q2) ^ ... ^ (P2 v Qn)
            ...
          ^ (Pm v Q1) ^ (Pm v Q2) ^ ... ^ (Pm v Qn)

If φ has the form ~(...), then:
  If φ has the form ~A for some variable A, then return φ.
  If φ has the form ~(~P), then return CONVERT(P).           // double negation
  If φ has the form ~(P ^ Q), then return CONVERT(~P v ~Q).  // de Morgan's Law
  If φ has the form ~(P v Q), then return CONVERT(~P ^ ~Q).  // de Morgan's Law

If φ has the form P -> Q, then:
  Return CONVERT(~P v Q).   // equivalent

If φ has the form P <-> Q, then:
  Return CONVERT((P ^ Q) v (~P ^ ~Q)).

If φ has the form P xor Q, then:
  Return CONVERT((P ^ ~Q) v (~P ^ Q)).

I translated it to JavaScript below, but am stuck on the AND and OR bits. I want to make sure I get this correct too.

The description of my “data model” / data structure is here.

/*
 * Any syntactically valid propositional formula φ must fall into
 * exactly one of the following 7 cases (that is, it is an instanceof
 * one of the 7 subclasses of Formula).
 *
 * @see https://www.cs.jhu.edu/~jason/tutorials/convert-to-CNF.html
 */

function convert(formula) {
  switch (formula.type) {
    case 'variable': return formula
    case 'conjunction': return convertConjunction(formula)
    case 'disjunction': return convertDisjunction(formula)
    case 'negation': return convertNegation(formula)
    case 'conditional': return convertConditional(formula)
    case 'biconditional': return convertBiconditional(formula)
    case 'xor': return convertXOR(formula)
    default:
      throw new Error(`Unknown formula type ${formula.type}.`)
  }
}

function convertConjunction(formula) {
  // CONVERT(P) must have the form P1 ^ P2 ^ ... ^ Pm, and
  // CONVERT(Q) must have the form Q1 ^ Q2 ^ ... ^ Qn,
  // where all the Pi and Qi are disjunctions of literals.
  // So return P1 ^ P2 ^ ... ^ Pm ^ Q1 ^ Q2 ^ ... ^ Qn.
}

function convertDisjunction(formula) {
  // CONVERT(P) must have the form P1 ^ P2 ^ ... ^ Pm, and
  // CONVERT(Q) must have the form Q1 ^ Q2 ^ ... ^ Qn,
  // where all the Pi and Qi are dijunctions of literals.
  // So we need a CNF formula equivalent to
  //    (P1 ^ P2 ^ ... ^ Pm) v (Q1 ^ Q2 ^ ... ^ Qn).
  // So return (P1 v Q1) ^ (P1 v Q2) ^ ... ^ (P1 v Qn)
  //         ^ (P2 v Q1) ^ (P2 v Q2) ^ ... ^ (P2 v Qn)
  //           ...
  //         ^ (Pm v Q1) ^ (Pm v Q2) ^ ... ^ (Pm v Qn)
}

function convertNegation(formula) {
  // If φ has the form ~(...), then:
  //   If φ has the form ~A for some variable A, then return φ.
  //   If φ has the form ~(~P), then return CONVERT(P).           // double negation
  //   If φ has the form ~(P ^ Q), then return CONVERT(~P v ~Q).  // de Morgan's Law
  //   If φ has the form ~(P v Q), then return CONVERT(~P ^ ~Q).  // de Morgan's Law
}

function convertConditional(formula) {
  // Return CONVERT(~P v Q).   // equivalent
  return convert({
    type: 'disjunction',
    base: {
      type: 'negation',
      formula: formula.base,
    },
    head: formula.head
  })
}

function convertBiconditional(formula) {
  // Return CONVERT((P ^ Q) v (~P ^ ~Q)).
  return convert({
    type: 'disjunction',
    base: {
      type: 'conjunction',
      base: formula.base,
      head: formula.head,
    },
    head: {
      type: 'conjunction',
      base: {
        type: 'negation',
        formula: formula.base,
      },
      head: {
        type: 'negation',
        formula: formula.head,
      },
    }
  })
}

function convertXOR(formula) {
  // CONVERT((P ^ ~Q) v (~P ^ Q)).
  return convert({
    type: 'disjunction',
    base: {
      type: 'conjunction',
      base: formula.base,
      head: {
        type: 'negation',
        formula: formula.head,
      },
    },
    head: {
      type: 'conjunction',
      base: {
        type: 'negation',
        formula: formula.base,
      },
      head: formula.head,
    }
  })
}

I have the AND and OR as a pair. So if you write in math like this:

A ∧ B ∧ C ∧ D ∧ E

That would be more like this in code:

A ∧ (B ∧ (C ∧ (D ∧ E)))

But the problem is, we might have arbitrary trees of formulas:

(((A ∧ B) ∧ (C ∧ D)) ∧ (E ∧ F))

Same with the OR. So how would you implement these functions convertDisjunction and convertConjunction, so they can handle that sort of tree data structure?

So what I would do is this:

function convertConjunction(formula) {
  let convertedBase
  if (formula.base.type === 'conjunction') {
    convertedBase = convertConjunction(formula.base)
  }
  let convertedHead
  if (formula.head.type === 'conjunction') {
    convertedHead = convertConjunction(formula.head)
  }
  ???
  // CONVERT(P) must have the form P1 ^ P2 ^ ... ^ Pm, and
  // CONVERT(Q) must have the form Q1 ^ Q2 ^ ... ^ Qn,
  // where all the Pi and Qi are disjunctions of literals.
  // So return P1 ^ P2 ^ ... ^ Pm ^ Q1 ^ Q2 ^ ... ^ Qn.
}

I get lost right at the beginning.

React table – dynamic group header

This is my data

  const data = [
    {
      date: "2021-01-01",
      options: [
        { isFirst: "y", name: "john" },
        { isFirst: "n", name: "Sam" }
      ]
    },
    {
      date: "2021-11-01",
      options: [
        { isFirst: "n", name: "TY" },
        { isFirst: "n", name: "joe" }
      ]
    }
  ];

My current UI:
enter image description here

This is what I want – the group header should be the date
enter image description here

How to do it?

App.js

import "./styles.css";
import React, { useMemo } from "react";

import MyTable from "./MyTable";

export default function App() {
  const data = [
    {
      date: "2021-01-01",
      options: [
        { isFirst: "y", name: "john" },
        { isFirst: "n", name: "Sam" }
      ]
    },
    {
      date: "2021-11-01",
      options: [
        { isFirst: "n", name: "TY" },
        { isFirst: "n", name: "joe" }
      ]
    }
  ];
  const columns = useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "Name",
            accessor: "name"
          },
          {
            Header: "First One",
            accessor: "isFirst"
          }
        ]
      }
    ],
    []
  );
  return (
    <div className="App">
      {data.map((d) => {
        return <MyTable data={d.options} columns={columns} />;
      })}
    </div>
  );
}

MyTable.js

import React from "react";
import styled from "styled-components";
import { useTable } from "react-table";

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`;

function DataTable(props) {
  const { data, columns } = props;
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <Styles>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return row.cells.map((cell) => {
                    return (
                      <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                    );
                  });
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </Styles>
  );
}

export default DataTable;

Codesandbox:
https://codesandbox.io/s/xenodochial-tamas-ns9ub

reconstruct an array in JS [duplicate]

How can I reconstruct the array1 to the array2. Could you please help me using map/reduce.
Thank you very much for your helps!

const array1 = [
{Count: 35,
Items: [
{Id:1, Category:'Account', Count:10, class:'A'},
{Id:2, Category:'Account', Count:5, class:'B'},
{Id:3, Category:'Account', Count:20, class:'B'},
]},
{Count: 75,
Items: [
{Id:1, Category:'Logout', Count:25, class:'A'},
{Id:2, Category:'Logout', Count:30, class:'B'},
{Id:3, Category:'Logout', Count:20, class:'C'},
]},
{Count: 85,
Items: [
{Id:1, Category:'Login', Count:10, class:'A'},
{Id:2, Category:'Login', Count:25, class:'B'},
{Id:3, Category:'Login', Count:50, class:'C'},
]}
]

const array2 = [
{name: 'Account', data: [10,5,20]},
{name: 'Logout', data: [25,30,20]},
{name: 'Login', data: [10,25,50]},
]

carousel is not working properly for second and third iteration in react js

I am creating a project in reactjs , where i am rendering carousel in loop, and carousel of first iteration is working perfectly but for other iteration’s it’s not.
can anybody suggest what is the wrong i am doing with the carousel.
this is my codesandbox link :- https://codesandbox.io/s/nice-heyrovsky-8yucf?file=/src/App.js

this is not the actual project so please ignore the empty data and other components.just look at the Prompts and card components.

CSS Float Question (Strange behaviors found)

Dears,

Below is my simple float program and I also attach a picture of the result. My question is: When the width in class “two” is 300px, the div 2 is moved next to the floated div 1, this is also my expectation. However, when i changed the width in class “two” from 300px to 200px, div 2 is kept under div 1, and div 3 is moved to overlap with div 2 (see the attached picture) Why? enter image description here

<html>`
<head>
<style>
.one{
    background: yellow;
    width: 200px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;
    Float: left;
    }

.two {
    background: rgb(55, 0, 255);
    width: 300px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;  
  }

.three {
    background: rgb(255, 0, 76);
    width: 200px;
    height: 50px;
    text-align: center; 
    box-shadow: inset 0 0 10px #000;
   }
 </style>
 </head>
 <body>
    <div class = "one">1</div>
    <div class = "two">2</div>
    <div class = "three">3</div>
 </body>
 </html>

Regex to clean a string and left only digits and the first dot in javascript

I want to replace with a regex any non digit character and the dots after the first one so

“–r43dsd.32.32” would be 43.3232

“–r4.3dsd.32.3.2” would be 4.33232

“–r43dsd.32.3.2” would be 43.3232

I tried this

.replace(/[^0-9.]/g, '')

but I don’t know how to remove the dots with replace and a regex. I read that I should use regex look ahead but I did not understand how to do it.

Is this achievable with only a regex and replace? I also created a function but I want to do it in a more clean way with a regex.

How to pass array of structs as argument on etherscan (tuple[])?

I’m trying to pass the format of array of structs as argument on smart contract write function on etherscan,

This is solidity example:

Info[] public info;

struct Info { 
    address userAddress;
    uint256 amount;   
    bool active; 
} 

enter image description here
Javascript example:

const data = [{0x0000, 10000000000, false},{0x11111, 20000000000, true}]

Can anyone convert this data example to tuple[] and provide it?
Thanks in advance

What is the easiest way to filter an object in javascript? [duplicate]

Yes, I know, there is already a question about how to filter objects in javascript, but look, I’m not asking how to do it, I’m asking about what would be the easiest way, the one which a noob like me could remember.

Before ask I spent a little time and after some tests I came up with theses solutions. They are examples but I cannot think about something better by now:

function queryHandlerOne(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];
  
  const entries = Object
    .entries(query)
    .filter(([key, _]) => fields.includes(key));

  return Object.fromEntries(entries);  
}
function queryHandlerTwo(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];

  const entries = Object
    .keys(query)
    .filter(key => fields.includes(key))
    .reduce((acc, key) => {
      acc[key] = query[key];
      return acc;
    }, {} as any);

  return entries;
}
function queryHandlerThree(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];

  const result = Object
    .keys(query)
    .filter(key => fields.includes(key))
    .map(key => [key, query[key]] as [string, any]);

  return Object.fromEntries(result);
}
function queryHandlerFour(query: any) {
  const fields = ["name", "featured", "price", "company", "rating"];
  const result = {};

  Object
    .keys(query)
    .filter(key => fields.includes(key))
    .forEach(key => Object.assign(result, { [key]: query[key] }));

  return result;
}

Scroll to bottom of HTML page only after dom finishes repainting

I have a function that I want to add a border to the bottom of the page, and then I want to scroll all the way down on the page.

here is my html for it

<div id="bottom-border></div>

Then with JavaScript I am essentially doing this to it

<div id="bottom-border" style="margin-bottom: 10rem;"></div>

after I added the border, then I want to scroll all the way down to then end of the page. Here is how I am doing all of this from JavaScript

        let bottomBorder = document.getElementById('bottom-border');
        bottomBorder.style.marginBottom = '10rem';
        window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'});

The problem is that it only scrolls down half way because the browser tries to scroll to the bottom while the browser is adding the margin-bottom, so the page only scrolls down half way.

I can do something like this, but I think this is a crummy way of doing it

        let bottomBorder = document.getElementById('bottom-border');
        bottomBorder.style.marginBottom = '10rem';

        let mobileKeyboardStyleSheet = document.getElementById('mobileKeyboardCSS')
        mobileKeyboardStyleSheet.disabled = false;

        setTimeout(() => {
            window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'});
        }, 1000);

That essentially waits a second before the browser finishes repainting it before trying to scroll down. However, this version gives a bad animation to the end user and it is not always reliable because some browsers take 0.5 seconds to paint and some browsers take 5 seconds to repaint.

I think it would be best if I could tell the browser to:

“do this code, and after it is finished being painted, then do this part of the code”

but I am unsure of how to do that.

Please let me know, thank you!

The exactly same idea puts a rectangle along the centerline of it though cannot put an image in the right place, how do I fix it?

I’m trying to draw some kind of a “ray” with Phaser 3.

I started the experiment with a simple rectangle to represent the ray. Here is the code.

  this.add.circle(90, 290, 10, 0xf00000);
  this.add.circle(290, 190, 10, 0xf00000);
  let angle = Phaser.Math.Angle.Between(90, 290, 290, 190)
  let reference = this.add.rectangle(90, 290, 600, 5, 0x00f000).setOrigin(0);
  reference.rotation = angle

The line doesn’t start at the center of its starting point.

enter image description here

I know the reason is Phaser draws the line (actually rectangle) starting top-left 90, 290 where the centerline of the rectangle is supposed to start at.

To fix it, I just need to change y of the top-left

let reference = this.add.rectangle(90, 290-5/2, 600, 5, 0x00f000).setOrigin(0);

where the 5 in 5/2 represents the height of the green rectangle.

And then I got what I want

enter image description here

However, things got complicated when I try to move something along the “ray”.

Here is the code.

var game = new Phaser.Game({
  scene: {
    preload: preload,
    create: create
  }
});

function preload() {
  this.load.path = 'https://raw.githubusercontent.com/liyi93319/phaser3_rpg/main/part1/assets/';
  this.load.atlas('bolt', 'bolt_atlas.png', 'bolt_atlas.json');
}

function create() {
  this.add.circle(90, 290, 10, 0xf00000);
  this.add.circle(290, 190, 10, 0xf00000);
  let angle = Phaser.Math.Angle.Between(90, 290, 290, 190)
  let reference = this.add.rectangle(90, 290 - 5 / 2, 600, 5, 0x00f000).setOrigin(0);
  reference.rotation = angle
  
  let bolt = this.add.sprite(90, 290-76/2, 'bolt', 'bolt_strike_0002').setOrigin(0);
  bolt.rotation = angle;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

I just added 2 lines of code based on the previously working code, with the same idea

  let bolt = this.add.sprite(90, 290-76/2, 'bolt', 'bolt_strike_0002').setOrigin(0);
  bolt.rotation = angle;

the 76 in 76/2 represents the height of the bolt (rectangle) I put.

290 represents the y coordinate of the center of the starting point.

The exactly same idea puts the green rectangle along the centerline of it though cannot put the bolt in the right place (along the centerline of the green rectangle), why is that? What am I missing?

enter image description here

Remove First and Last Double Quote From JSON Array

Here i have one big array that has multiple arrays inside. I need to remove double quotes from each array. I tried all different methods to pull out quotes but none seem to work.

Current code produces this result:

[
  ["1,jone,matt,ny,none,doctor"],
  ["2,maria,lura,nj,some,engineer"],
  ["3,paul,kirk,la,none,artist"]
]
    const storeArray = [];

    for(var i = 0; i < results.length; i++) {

      var finalArray = results[i].id + "," + results[i].name + "," + results[i].lastname + "," + results[i].address + "," + results[i].status + "," + results[i].about;

      storeArray.push([finalArray]);
    }

    res.send(storeArray);

Javascript: Creating dictionary array using variables for keys and values

I am trying to create a dictionary from some lists using the .push() method.

The result I am trying to achieve is:

{
  "departTo": {
    1: 1.159,
    2: 4.156,
    3: 9.185,
    3: 10.158,
    4: 2.158
  },
  "departTo": {
    1: 2.586,
    2: 5.518,
    3: 11.584,
    3: 7.819,
    4: 3.991
  }
}

Below is a sample of code of what I am trying to do:

console.group("Running Script 1...");

var select_array = [];
var arrive_from, info

var selection_type = ["departTo", "arriveFrom"];
var data_lists_depart = [[1, 1.159], [2, 4.156], [3, 9.185], [4, 10.158], [5, 2.158]];
var data_lists_arrive = [[1, 2.586], [2, 5.518], [3, 11.584], [4, 7.819], [5, 3.991]];

selection_type.forEach(function (selection, i) {
    console.log("selection", i + ": ", selection);
    if (selection === "departTo") data_lists = data_lists_depart;
    else if (selection === "arriveFrom") data_lists = data_lists_arrive;
    data_lists.forEach(function (data_list, ii) {
        console.log("   data_list", ii + ": ", data_list);
        key = data_list[0];
        val = data_list[1];
        select_array.push({selection: {key: val}});
    })
})
console.log("select_array: ", select_array);

console.groupEnd("Running Script 1...");

The result I am getting from the above code is:

[
  {"selection": {"key": 1.159}}, 
  {"selection": {"key": 4.156}}, 
  {"selection": {"key": 9.185}}, 
  {"selection": {"key": 10.158}}, 
  {"selection": {"key": 2.158}}, 
  {"selection": {"key": 2.586}}, 
  {"selection": {"key": 5.518}}, 
  {"selection": {"key": 11.584}}, 
  {"selection": {"key": 7.819}}, 
  {"selection": {"key": 3.991}}
]

Any assistance in getting this into the format I need will be greatly appreciated.
Thank you.