How am I getting 339 as output of console.log(3+’4’+5-6) ?
can anyone please explain me?
Category: javascript
Category Added in a WPeMatico Campaign
How to test upload file in ts
I am trying to test an input tag but I want to test the content of the uploaded file.
here is the code –
<input
data-testid="file-input"
type="file"
accept=".csv, .tsv"
onChange={(event) => {
if (event.target.files !== null) {
setCsvFile(event.target.files[0]);
let reader = new FileReader();
var content: string | ArrayBuffer | null | undefined;
reader.onload = function () {
content = reader.result;
console.log(reader.result);
};
reader.onerror = function () {
console.log(reader.error);
};
reader.readAsText(event.target.files[0]);
}
}}
/>;
How can I unit test what is being read by FileReader on file upload?
How to send multiple response for single request in nodejs?
I am learning nodejs and angular. I am sending image to the server and processing them like changing the brightness and other things using nodejs.
Currently I am sending the response after completing the process for all files. But I want to send response for the file which have processed then next response for the next processed file and continue for this multiple files.
Then how to do that in nodejs with angular?
How to access JSON API from a link in another API React Native
I want to Ftech the Data on The “link” on a New Screen [Edit] This what I did and What I didn’t
call api to: https://flow.simpas.ai/hortus/paysagiste/category?businessid=0899607494
Done
- I receive a json that will allow me to display The Data on My DataTable
Done - When we click on a line of the Datatable
Done - I should call api via the link ‘link’ [‘link’ is in the first json and is a link to a second json]
Not Yet - I should Display the Data on Link on a New Screen Edit
Not Yet
if Someone Can Help in this 2 last Step I’ll Be thankful
This is The Code Of The List Screen:
import React, { useState,useEffect } from 'react';
import { StyleSheet, SafeAreaView, ScrollView,Text, View, Modal,FlatList } from 'react-native';
import { DataTable } from 'react-native-paper';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
const List = ({navigation}) => {
const [data,setData] = useState([])
const [loading,setLoading]= useState(true)
const fetchData = ()=>{
fetch("https://flow.simpas.ai/hortus/paysagiste/category?businessid=0899607494")
.then(res=>res.json())
.then((json)=>setData(json))
.catch((error)=>console.error(error))
.finally(()=>setLoading(false))
}
useEffect(()=>{
fetchData()
},[])
const LinkCall = (item)=>{
fetch("https://flow.simpas.ai/hortus/paysagiste/category?businessid=0899607494")
.then(res=>res.json())
.then((json)=>setData(json))
.catch((error)=>console.error(error))
.finally(()=>setLoading(false))
}
useEffect(()=>{
LinkCall()
},[])
const RenderCollection = (item) =>{
return(
<DataTable.Row style={styles.tableRow} key={item.businessid}>
<DataTable.Cell textStyle={{color: '#777777',fontFamily: 'Roboto'}} onPress={() => navigation.navigate("Edit",{item})} >{item.businessid}</DataTable.Cell>
<DataTable.Cell textStyle={{color: '#FEB296', fontFamily: 'Roboto'}}>{item.title}</DataTable.Cell>
<DataTable.Cell textStyle={{color: '#777777', fontFamily: 'Roboto'}}>{item.price}</DataTable.Cell>
</DataTable.Row>
)
}
return (
<SafeAreaView style={{ flex: 1}}>
<ScrollView
contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
<Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold', fontFamily: 'Roboto',textAlign: 'center'}}>
List of Companies
</Text>
<Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10, fontFamily: 'Roboto', textAlign: 'center'}}>
Check Our Companies Details
</Text>
<DataTable style={styles.container} >
<DataTable.Header style={styles.tableHeader} >
<DataTable.Title textStyle={{color: '#fff',fontSize: 16, fontFamily: 'Roboto'}}>id</DataTable.Title>
<DataTable.Title textStyle={{color: '#fff',fontSize: 16, fontFamily: 'Roboto'}}>Title</DataTable.Title>
<DataTable.Title textStyle={{color: '#fff',fontSize: 16, fontFamily: 'Roboto'}}>body</DataTable.Title>
</DataTable.Header>
</DataTable>
<FlatList
data={data.articles}
renderItem={({item})=>{
return RenderCollection(item)
}}
keyExtractor={item=>item.businessid}
onRefresh={()=>fetchData()}
refreshing={loading}
/>
</ScrollView>
</SafeAreaView>
);
};
export default List;
const styles = StyleSheet.create({
container: {
padding: 0,
},
tableHeader: {
backgroundColor: '#50E3C2',
},
tableRow: {
backgroundColor: '#fff',
},
});
How can I force a user to indicate that they are switching from operator to operator
I’m creating a JS module that serves as a ‘programming language’ This programming language interprets human words and is supposed to translate it into Javascript.
The programming language is going to be strict on grammar, similarly to other programming languages, and that’s what the question here is here to accomplish.
In my programming language, you can write your program many different ways, but to keep mines clean, I like to split it off in chunks for readability. This block of code shown here:
...
add 2 and 2
multiply by 5
...
Would spew out:
20
It’s working, but if we are trying to be strict on grammar as well, we would have to ask this question:
- Multiply what by 5? The result of the previous math equation, or is the user initiating another equation?
And if we were using the result of the previous math equation, the code would need to look something like this:
...
add 2 and 2
then multiply the result by 5
...
Still spewing the same result of:
20
How can I accomplish this goal?
Full Source Code
source.js:
Array.prototype.remove = function(value) {
for (var i = this.length; i--; )
{
if (this[i] === value) {
this.splice(i, 1);
}
}
}
// from https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number
function isNumeric(str) {
if (typeof str != "string") return false
return !isNaN(str) && !isNaN(parseFloat(str))
}
function isOperand(token) {
const ops = ["add", "multiply", "subtract", "divide"]
if (ops.includes(token)) {
return true
}
return false
}
function interpret(input) {
const tokens = input.split(' ') // in fancy programming language terms,
// this is a lexical analysis step
// note that we are not supporting things like
// double spaces, something to think about!
tokens.remove('n')
tokens.remove('')
console.log(tokens)
let state = 0 // we are keeping the results from our operation here
for (i = 0; i < tokens.length; i++) {
const t = tokens[i] // to keep things shorter
if (!isOperand(t)) {
throw new Error(`expected operand token, got: ${t}`)
}
// all operators are binary, so these variables will hold the operands
// they may be two numbers, or a number and the internal state
let a, b;
const next = tokens[i + 1]
if (next == "by") {
// we should add the next token (hopefully a number!) to the state
a = state
b = parseFloat(tokens[i + 2])
i += 2 // very important! the two tokens we read should be skipped
// by the loop. they were "consumed".
}
else if (isNumeric(next)) {
const and = tokens[i + 2] // this should be the "and"
if (and != "and") {
throw new Error(`expected "and" token, got: ${and}`)
}
a = parseFloat(next)
b = parseFloat(tokens[i + 3])
i += 3 // in this case, we are consuming more tokens
} else {
throw new Error(`unexpected token: ${next}`)
}
switch (t) {
case "add":
state = a + b
break;
case "multiply":
state = a * b
break;
case "subtract":
state = a - b
break;
case "divide":
state = a / b
break;
}
}
return state
}
function out(main) {
console.log(interpret(main))
}
module.exports = {out}
index.js:
const cjs = require('./source.js')
var main = `
add 2 and 2
multiply by 5
`
cjs.out(main)
How to use native modules for Pixi 6?
I am building a PixiJS game with native ES modules. There is no compiler like Parcel or Rollup. This works pretty well, for example a sprite class looks like this
export class Block extends PIXI.Sprite {
speed = 5
constructor(texture) {
super(texture)
}
update(){
this.x -= this.speed
}
}
The problem is that the Pixi library is still loaded using a script tag:
<script src="https://pixijs.download/release/pixi.min.js"></script>
If this could also be loaded as a native module, then I would get much better code completion / syntax checking in VS code. I found a native ES module for Pixi 5, then you can do:
import { Sprite } from './pixi.mjs' // SADLY THIS IS PIXI 5
Does anyone know how to do this with Pixi 6?
By the way, installing+importing pixi.js into node_modules WILL give correct code completion, but of course the project will not run in the browser because there is no module bundler…
Incidentally I found that there is some sort of pixi.esm file in the node_modules folder. Is that in any way related to this problem?
Create HTML table contains JSON array
I want to create an HTML table containing two columns the first col is servicepoint and the second one is called watchid the both columns are in a JSON array called final and I want to insert the array data to an HTML table so I used this javascript function
constructTable(selector,data)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
<script src='https://unpkg.com/[email protected]/dist/tesseract.min.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src='excelexportjs.js'></script>
<script src='mains.js'></script>
<div class="container mt-5 ">
<div id="dvjson"></div>
<p id = "GFG_UP" style="font-size:15px;"></p>
<button type="button" onclick="constructTable('#table')"class="btn btn-danger">Convert To Table</button>
<table align="center" id="table" border="1"></table>
</div>
</head>
<body>
</body>
</html>
mains.js
(async () => {
const { data: { text } } = await readFile('sd.png');
const data = await
parseDataFromTextAndPropertyNames(text, ['servicepoint', 'watchid']);
document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
const final = JSON.stringify(data);
constructTable('#table',final);
$("#table").excelexportjs({
containerid: "table",
datatype: 'table',
dataset: data,
columns: getColumns(data)
});
const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);
console.log({ result });
})();
// construct JSON array to HTML Table
function constructTable(selector,data) {
// Getting the all column names
var cols = Headers(data, selector);
// Traversing the JSON data
for (var i = 0; i < data.length; i++) {
var row = $('<tr/>');
for (var colIndex = 0; colIndex < cols.length; colIndex++)
{
var val = data[i][cols[colIndex]];
// If there is any key, which is matching
// with the column name
if (val == null) val = "";
row.append($('<td/>').html(val));
}
// Adding each row to the table
$(selector).append(row);
}
}
function Headers(data, selector) {
var columns = [];
var header = $('<tr/>');
for (var i = 0; i < data.length; i++) {
var row = data[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
// Creating the header
header.append($('<th/>').html(k));
}
}
}
// Appending the header to the table
$(selector).append(header);
return columns;
}
The above code is creating a table with only one column named 0 and the rows are the JSON final string
(async() => {
const {
data: {
text
}
} = await readFile('sd.png');
const data = await
parseDataFromTextAndPropertyNames(text, ['servicepoint', 'fuckyou']);
document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
const final = JSON.stringify(data);
constructTable('#table', final);
$("#table").excelexportjs({
containerid: "table",
datatype: 'table',
dataset: data,
columns: getColumns(data)
});
const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);
console.log({
result
});
})();
// construct JSON array to HTML Table
function constructTable(selector, data) {
// Getting the all column names
var cols = Headers(data, selector);
// Traversing the JSON data
for (var i = 0; i < data.length; i++) {
var row = $('<tr/>');
for (var colIndex = 0; colIndex < cols.length; colIndex++) {
var val = data[i][cols[colIndex]];
// If there is any key, which is matching
// with the column name
if (val == null) val = "";
row.append($('<td/>').html(val));
}
// Adding each row to the table
$(selector).append(row);
}
}
function Headers(data, selector) {
var columns = [];
var header = $('<tr/>');
for (var i = 0; i < data.length; i++) {
var row = data[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
// Creating the header
header.append($('<th/>').html(k));
}
}
}
// Appending the header to the table
$(selector).append(header);
return columns;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
<script src='https://unpkg.com/[email protected]/dist/tesseract.min.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src='excelexportjs.js'></script>
<script src='mains.js'></script>
<div class="container mt-5 ">
<div id="dvjson"></div>
<p id="GFG_UP" style="font-size:15px;"></p>
<button type="button" onclick="constructTable('#table')" class="btn btn-danger">Convert To Table</button>
<table align="center" id="table" border="1"></table>
</div>
Promise telegraf sequelize>?
I want to output the quantity and the keys from the database, but I get in response,
What should I do
It displays information in the console, but not in ctx.reply
await ctx.deleteMessage(msg.message_id);
const info = {
kkey: await apikeyadd.count()
}
const info2 = {
kkey: await apikeyadd.findAll({raw: true})
.then (kkey => {
console.log(kkey);
})}
await ctx.replyWithHTML(`<b>Welcome! <code>${ctx.message.from.first_name}</code></b>nnn`+
`Ключей в базе: ${info}n`+
`nnnnnnnnnnnnnnLast create: ${info2}`,+
'test', Markup.inlineKeyboard([
Markup.button.callback("back", "cancel")
]))}
model:
const apikeyadd = sequelize.define('ukey', {
kkey: {
type: DataTypes.STRING,
allowNull: false
},
namekey: {
type: DataTypes.STRING,
allowNull: false
}
}, {
tableName: 'ukey'
});
module.exports = apikeyadd;
want double back slash in string after storing it in variable for regex purpose in Javascript
expected output: “(b|(|[)([0-9.A-z-/~#:~:=%,.&?’()])()|]|b)”
but received output: “(b|(|[)([0-9.A-z-/~#:~:=%,.&?’()])()|]|b)“
var contents = "\b|\(|\[";
var cont ="\("+contents+")([0-9\.A-z\-\/\~\#\:\~\:\=\%\,\.\&\?\’\(\)]*)(\)|\]|\b)*";
console.log(cont);
//expected output: "\("\b|\(|\[")([0-9\.A-z\-\/\~\#\:\~\:\=\%\,\.\&\?\’\(\)]*)(\)|\]|\b)*"
//but received output: "(b|(|[)([0-9.A-z-/~#:~:=%,.&?’()]*)()|]|b)*"
Function taking unlimited number of parameters and invokes callbacks one by one Javascript
So, I have to rewrite this code by some rules:
mix(() => {
return 0;
}, (prev) => {
return prev + 1;
}, (prev) => {
return prev * 2;
})
So it takes the returned value of the callback function and uses it as a parameter. What I have to do is:
Write an arrow function that invokes callbacks one by one. Each callback as a parameter gets the result of the previous callback invoking. The first callback doesn’t get any parameters.
Write a program that, given a sequence of integer values, encodes it using the delta compression algorithm
Can someone please help? Python or Javascript preferably
Python3 Predefined code:
import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...
for line in sys.stdin:
print(line, end="")
Javascript Predefined code:
process.stdin.resume();
process.stdin.setEncoding('utf8');
var stdin = '';
process.stdin.on('data', function (chunk) {
stdin += chunk;
}).on('end', function() {
var lines = stdin.trim().split('n');
for(var i=0; i<lines.length; i++) {
process.stdout.write(lines[i]);
}
});
Task:
Delta Compression – Encoding
Programming challenge description:
In data transmission, delta compression is used to encode data as a difference between successive values (e.g. bytes), rather than using the values themselves.
Let’s look on an example of how to encode the byte sequence 28 30 33 30 28 29 31 66 65 65 65 64 using delta compression. The first value is simply copied from the original data to the delta encoded output stream. Each subsequent value in the output stream is equal to the difference (i.e. delta) between the corresponding value in the input stream and the prior value in the input stream.
The image in the attachments tab illustrates the encoding process.
Write a program that, given a sequence of integer values, encodes it using the delta compression algorithm.
Input:
A source data stream expressed as a space-delimited list of integers. For example:
28 30 33 30 28 29 31 66 65 65 65 64
Output:
Print a delta encoded output stream as a space-delimited list of integers. For example, the input above should result in:
28 2 3 -3 -2 1 2 35 -1 0 0 -1
Test 1
Test Input
Download Test 1 Input
28 30 33 30 28 29 31 66 65 65 65 64
Expected Output
Download Test 1 Output
28 2 3 -3 -2 1 2 35 -1 0 0 -1
Test 2
Test Input
Download Test 2 Input
5 6 7 8 9 9 9 9 8 7 6 5
Expected Output
Download Test 2 Output
5 1 1 1 1 0 0 0 -1 -1 -1 -1
Test 3
Test Input
Download Test 3 Input
14 16 14 11 11 10 14 14 13 14 18 16 13 10 8
Expected Output
Download Test 3 Output
14 2 -2 -3 0 -1 4 0 -1 1 4 -2 -3 -3 -2
Test 4
Test Input
Download Test 4 Input
-123 -134 -128 -114 -115 -118 -114 -105 -104 -99 -105 -102 -112 43 36 36 50 41 56 59 70 69 59 51 56
Expected Output
Download Test 4 Output
-123 -11 6 14 -1 -3 4 9 1 5 -6 3 -10 155 -7 0 14 -9 15 3 11 -1 -10 -8 5
Can someone help me? I am new to programming and this is what I’ve been slapped with.
How to save data to database by using bootstrap modal and fetch api
I’m trying to get data from bootstrap modal input and save that data to database when I click the “Create” button in modal. But when I click the create button nothing happens. Modal stays on screen and data won’t pass to database. I put a “p” element before name input that is hidden by default and becomes visible if user clicks the create button with an empty input. It also doesn’t work. I would be grateful if someone could tell me where the problem is. Here is my code;
HTML:
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
//...
<!-- Modal -->
<button type="button" id="createItemButton" class="btn btn-info col-2" data-bs-toggle="modal"
data-bs-target="#createItemModal" data-bs-whatever="@mdo">Create Item</button>
<div class="modal fade" id="createItemModal" data-bs-backdrop="static" tabindex="-1"
aria-labelledby="createItemModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createItemModalLabel">New Todo Item</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form>
<div class="mb-3">
<p id="warning">*Please fill in all fields</p>
<label for="item-name" class="col-form-label">Name:</label>
<input type="text" class="form-control" id="item-name">
</div>
<div class="mb-3">
<label for="item-description" class="col-form-label">Description:</label>
<textarea class="form-control" id="item-description"></textarea>
</div>
<div class="mb-3">
<label for="deadline" class="col-form-label">Deadline:</label>
<input type="date" name="deadline" id="deadline">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button id="save-item-button" type="button" class="btn btn-info">Create</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
Javascript:
import Modal from 'bootstrap/js/dist/modal';
const itemButton = document.getElementById('createItemButton');
const itemModal = document.getElementById('createItemModal');
const saveItemButton = document.getElementById('save-item-button');
const warning = document.getElementById('warning');
const modal = new Modal(itemModal); // Instantiates your modal
itemButton.addEventListener('click', () => {
modal.show(); // shows your modal
});
saveItemButton.addEventListener('click', () => {
const name = document.querySelector('#item-name').value;
const description = document.querySelector('#item-description').value;
const deadline = document.querySelector('#deadline').value;
if (name == "" || description == "" || deadline == "")
warning.style.visibility = "visible";
else {
fetch("http://localhost:8080/api/lists/name/" + listName)
.then(response => response.json())
.then(list => {
saveItemToDB(name, description, deadline, list.id);
});
modal.hide();
alert("Item saved!");
}
});
function saveItemToDB(name, description, deadline, listId) {
fetch("http://localhost:8080/api/items/save/" + listId, {
method: "POST",
body: JSON.stringify({
"name": name,
"description": description,
"deadline": deadline,
"status": false,
"dependencies": [],
"todo_list_id": listId
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
}
})
.then(response => response.json());
}
How to manipulate multiple element’s styles with a single event listener? [duplicate]
This is probably very simple, but I cannot make it work.
I have 2 headings with the same class
<h1 class="heading-title">Hyperspace</h1>
<h1 class="heading-title">Hyperspace</h1>
I also have a button that I want to change both the headings color when I click it
const customColor1Btn = document.querySelector(".custom-color-1");
const headings = document.querySelectorAll(".heading-title");
customColor1Btn.addEventListener("click", function () {
headings.style.color = "red";
});
It works when I change the color of just 1 heading, but I can never make an event listener work with more than 1 element. I need 1 button click to manipulate multiple element’s styles.
How can I make it work?
why is next redux wrapper Hydrate action running multiple times?
I am starting a new next js project,we are migrating from a normal react app to a next app.
we intend to use redux toolkit for our global state management and we are using server side rendering.so we came across next-redux-wrapper npm package which looked like it solves most of our problems with redux and ssr but form some reason when ever we use server side rendering on one of the pages the HYDRATE action from next-redux-wrapper is getting called atleast twice sometimes even 4 times.What exactly is going wrong because the article i referred to seems to work fine,i have attached my Redux store details and the Redux slice details,and my getServerSideProps function details.
import { createStore, applyMiddleware, combineReducers } from "redux";
import count from "../ReduxSlices/CounterSlice";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import { configureStore } from "@reduxjs/toolkit";
const combinedReducer = combineReducers({
count,
});
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
count: {
count: state.count.count + action.payload.count.count,
},
};
return nextState;
} else {
return combinedReducer(state, action);
}
};
export const makeStore = () =>
configureStore({
reducer: reducer,
});
export const wrapper = createWrapper(makeStore, { debug: true });
and my Redux slice is
import { createSlice } from "@reduxjs/toolkit";
import { HYDRATE } from "next-redux-wrapper";
const initialState = {
count: 0,
};
const counterSlice = createSlice({
name: "counter",
initialState: initialState,
reducers: {
increment: (state) => {
state.count = state.count + 1;
},
},
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;
and finally this is how i dispatch an action inside getServerSideProps
export const getServerSideProps = wrapper.getServerSideProps(
(store) => async () => {
store.dispatch(increment());
console.log("server", new Date());
}
);
The console log is logging only once but the HYDRATE action is getting dispatched atleast two times…any insight will be helpful,thank you.
How to sort array of objects according to epoch time in JavaScript
I want to arrange the data which I am getting from the API according to the time.
Here is one of the objects inside the array.
{
"orderId": "xxxxxxxxxxxxx",
"amount": 10,
"status": "CREATED",
"transactionTime": 1651498914,
"type": "ADD",
"mode": "UPI",
"bankAccountId": {
"bankAccountNumber": "xxxxxxxxxxxxx",
"ifsc": "XXXX XXXX XXXX"
}
}
I want to arrange the array in descending order according to the transactionTime which is an epoch time.
My initial approach.
data.map((item) => item.transactionTime)
.sort()
.reverse()
.map((item) => {
return data.find((i) => i.transactionTime == item);
})
This code is perfectly working but as you can see, it is not a good way to do this.
So I want a more optimized solution. Someone suggested using a priority queue.
