Category: javascript
Category Added in a WPeMatico Campaign
Convert object with arrays to array of objects using Ramda
Example input:
const obj = {
paths: ['path1', 'path2'],
thumbnails: ['thumb1', 'thumb2'],
sizes: [
[100, 200],
[120, 220],
],
};
Expected output:
const result = [
{
path: 'path1',
thumbnail: 'thumb1',
size: [100, 200],
},
{
path: 'path2',
thumbnail: 'thumb2',
size: [120, 220],
},
];
Bonus points for:
const result = [
{
path: 'path1',
thumbnail: 'thumb1',
width: 100,
height: 200,
},
{
path: 'path2',
thumbnail: 'thumb2',
width: 120,
height: 220,
},
];
How would I achieve this with Ramda?
Passing arguments to google cloud functions
I have a function I deployed to the cloud which looks like this.. im trying to pass arguments from a node js app trigger the function but im not sure how to go about it. Any help or advice would be appreciated.
exports.discordFeedback = (req,res)=>{
const { MessageEmbed, WebhookClient, ModalSubmitInteraction, Collector } = require('discord.js');
var webhookId = "**********";
var webhookToken = "***********";
var version = "***" ;
var color;
let store = req.query.store || "Error...";
let itemName = req.query.item_name || "Unknown Error...";
let itemPrice = req.query.item_price || "$???.??";
let botMode = req.query.bot_mode || "Unknown...";
let itemImageUrl = req.query.image_url || "https://mir-s3-cdn-cf.behance.net/project_modules/1400/9aca1078350973.5ca28ba956e23.jpg";
}
scroll navbar out of view when page is ready using jquery
<div id="navbar"> ... </div>
<div id="mainpage" style="height: 100vh;"> ... </div>
<div id="footer"> ... </div>
when the page is ready, i want the jquery to scroll out the complete navbar div, for this,
i am currently using –
$(document).ready(function(){
var navHeight = $('#navbar').height();
console.log(navHeight);
$('body,html').animate({scrollTop: navHeight}, 400);
})
this only lefts some portion of navbar in view,
there is enough area left in footer to scroll.
i dont now why is this happening
Cant write to files inside of .then()?
I had a question about some code that i had working earlier, but now decides it doesnt want to work at all. Basically, I have a promise that returns me an array of data. I’ll explain whats happening at the bottom of the code.
function mkdir(path){
return new Promise(function(resolve,reject){
fs.mkdir(path, { recursive: true },function(err){
if(err){console.log(err)}
})
return resolve()
})
}
function writeFile(file,content){
return new Promise(function(resolve,reject){
fs.writeFile(file, content, function(err){
if(err){console.log(err)}
return resolve()
})
})
}
function rawData(socket){
var mintDataArray = []
return new Promise(function(){
for (let i = 1; i < 13; i+= 1) {
getdat(i).then(function(r){
//mintDataArray.push(r)
for(o in r){
var dataurls = []
dataurls.push(r[o].discord_url,r[o].magic_eden_url,r[o].twitter_url)
//socket.emit('twitterFollowers',r[o])
const ProjectData = {
"mintDate": 0 || "",
"name":"",
"stock":0,
"links":[],
"mintTime": 0 || "",
"PricePlusDescription":0 || ""
}
if(r[o].mintDate != null){
ProjectData.mintDate = moment.utc(r[o].mintDate).format("MMMM Do")
}else{
ProjectData.mintDate = "No date specified yet"
}
ProjectData.name = r[o].name
ProjectData.stock = r[o].supply
ProjectData.links.push(dataurls)
ProjectData.PricePlusDescription = r[o].price
mintDataArray.push(ProjectData)
}
}).then(function(socket){
//CollectionSorter(mintDataArray)
for(i in mintDataArray){
var data = mintDataArray[i]
//console.log(data) // <----- This prints out the data that needs to be written to files.
var MintDateFolder = __dirname + "/UpcomingCollections/" +data.mintDate
if(!fs.existsSync(MintDateFolder)){
console.log('huh?')
mkdir(__dirname + '/UpcomingCollections/'+data.mintDate)
}
writeFile(MintDateFolder +"/"+data.name,JSON.stringify(data))
}
})
}
//socket.emit('twitterFollowers',mintDataArray)
})
}
So what the code is supposed to do, is check to see if that directory first exists in general. If it doesnt, then create the new directory. Then after that, its supposed to write files to it (not just that directory, but to other directories as well). It doesnt create the directory if it doesnt exists and it doesnt even write to it if i manually create the directory, however it does write to the other directories. I’m really not sure with this one because I had this working earlier, where it was creating the directory if it didn’t exist. so i’m not sure what i messed up on.
I recently made mkdir and writefile functions and i thought they were the issue, because when i had this working I was just using fs.mkdir and fs.writefile. However, i went and tried again without those functions and i was still having the same troubles. I thought about making another promise to check if the directory existed but I already have quite a few nested promises.
Slider to go to the end from index[0] React Typescript project
I am working on a personal project using React.js and Typescript. I build a slider that works fine so far, but there is one issue. When the slider is in the position 1, thus index[0], and the user press the “back” button to go back one more slide, I would like the slider to go to the end.
This is the code:
import { useEffect, useRef, useState } from "react";
import "./styles.css";
const colors: string[] = ["#0088FE", "#00C49F", "#FFBB28"];
export default function App() {
const [activeIndex, setActiveIndex] = useState<number>(0);
const timeOutRef = useRef<null | number>(null);
const delay: number = 2500;
const resetTimeOut = () => {
if (timeOutRef.current) {
clearTimeout(timeOutRef.current);
}
};
const handleArrowRight = () => {
if (activeIndex === colors.length - 1) {
setActiveIndex(0);
} else setActiveIndex(activeIndex + 1);
};
const handleArrowLeft = () => {
if (activeIndex === 0) return;
setActiveIndex(activeIndex - 1);
};
useEffect(() => {
resetTimeOut();
timeOutRef.current = setTimeout(
() =>
setActiveIndex((prevIndex: number) =>
prevIndex === colors.length - 1 ? 0 : prevIndex + 1
),
delay
);
return () => {
resetTimeOut();
};
}, [activeIndex]);
return (
<div className="App">
<div className="slideVisible">
<div
className="slideContainer"
style={{ transform: `translate3d(${-activeIndex * 100}%, 0, 0)` }}
>
{colors.map((colored, index) => (
<div
key={index}
className="slide"
style={{ backgroundColor: colored }}
></div>
))}
</div>
<button onClick={handleArrowLeft} className="leftArrow">
Back
</button>
<button onClick={handleArrowRight} className="rightArrow">
Next
</button>
<div className="slideDotsContainer">
{colors.map((_, index) => (
<div
key={index}
className={`slideDots ${activeIndex === index ? "active" : ""}`}
onClick={() => setActiveIndex(index)}
></div>
))}
</div>
</div>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Also, this is a CodeSandBox link with the css on it
How to merge elements of two string arrays in javascript?
let’s say we have two JavaScript arrays like this:
var firstNameArray = [“Jack”, “Indiana”, “James”];
var lastNameArray = [“Sparrow”, “Jones”, “Bond”];
I want the output to be:
var result = [“Jack Sparrow”,”Indiana Jones”,”James Bond”];
Note: firstNameArray & lastNameArray can have dynamic values*
How do I merge elements of two arrays in JavaScript to get this result?
How can I formulate this to end when “-1” is entered?
This is the last part of this assignment and my brain is melting a bit. I am brand new to everything coding and would love some input.
*Here is the prompt:
Use a while loop to process user entered numbers.
Inform the user to enter a positive number to be added to the total or -1 to end.
With each iteration of the loop, add the user entered value to a running total.
End the loop when the user enters -1 and do not add that value to the running total.
Once the loop ends, print the total of the numbers entered, (excluding the sentinel value -1.)
Define the appropriate variables needed.
*Needs to be javascript
Thanks in advance.
Timer counter down in javascript (ASP.Net)
I use below code to make a timer counter down, the console log works well (10,9,8,…) but I can’t see the changes on the label
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
function counterDown(count) {
console.log("JLog: ", count);
if (count > 1) {
var lbl = document.getElementById('<%= lblTimer.ClientID %>');
lbl.innerText = count;
sleep(1000);
counterDown(count - 1);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<br /><br />
<asp:TextBox ID="txtUserName" runat="server" Height="20px" Width="120px"></asp:TextBox><br /><br />
<asp:TextBox ID="txtPassword" runat="server" Height="20px" Width="120px"></asp:TextBox><br /><br />
<asp:Button runat="server" OnClientClick="counterDown(10);" Text="Start Timer" />
<br /><br />
<asp:Label runat="server" id="lblTimer" Text="--"></asp:Label><br /><br />
</form>
</body>
</html>
How can I fix it?
Angular – Error with cheerio package? “You may need an additional loader to handle the result of these loaders”
I am suddenly facing this issue that seemingly came out of nowhere. The project I am working on in my company is rather large and we are using a micro frontend architecture. I was working in one branch yesterday and after building and pushing my code, I checked out to another branch to check something and then went back to the original branch I was in. After trying to serve the application again, I was faced with this error. It seems everyone else on the team is getting this error, too. Even those who haven’t pulled the code I pushed.
Here is the error:
Error: ./node_modules/cheerio/node_modules/htmlparser2/lib/esm/index.js 59:9
Module parse failed: Unexpected token (59:9)
File was processed with these loaders:
- ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
- ./node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
| return getFeed(parseDOM(feed, options));
| }
export * as DomUtils from “domutils”;
| // Old name for DomHandler
| export { DomHandler as DefaultHandler };
Error: ./node_modules/cheerio/node_modules/parse5/dist/index.js 6:9
Module parse failed: Unexpected token (6:9)
File was processed with these loaders:
- ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
- ./node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
| export { serialize, serializeOuter } from ‘./serializer/index.js’;
| /** @internal */
export * as foreignContent from ‘./common/foreign-content.js’;
| /** @internal */
| export * as html from ‘./common/html.js’;
I’ve tried:
- updating cheerio
- deleting node_modules and package-lock, then running npm i
- deleting cheerio
- reverting back to before I pushed my code
Really not sure what else to do. This is my first stack overflow question so sorry if I’m missing any necessary info.
Hide show div elements on click in javascript but I want the boxes to stay at their respective position
So far, I was able to do the hide and show but the problem is if we click the button for the blue box to be hidden, the red box will go to the place of the blue box. Hence, it may cause confusion.
I want that if we click that button, the blue box will just disappear and the red box should stay put, stay in its original position/location. I hope that makes sense.
<html>
<head>
<!--- styling these divs-->
<style>
#greendiv {
width: 30%;
height: 50%;
background-color: green;
float: left;
}
#bluediv {
width: 30%;
height: 50%;
background-color: blue;
float: left;
}
#reddiv {
width: 30%;
height: 50%;
background-color: red;
float: left;
}
</style>
</head>
<body>
<!------- green -------->
<input type="button" value="GREEN" id="button4green" style="position: absolute; left: 13%;">
<div id="greendiv">
</div>
<!------- blue -------->
<input type="button" value="BLUE" id="button4blue" style="position: absolute; Left:43%">
<div id="bluediv">
</div>
<!------- red -------->
<input type="button" value="RED" id="button4red" style="position: absolute; Left:74%">
<div id="reddiv">
</div>
<!----- Now add the JavaSCript----->
<script>
// start for the green here -----------------------------------------------------
document.getElementById("button4green").addEventListener("click", function() // made a function to call on onclicking
{
let greenbox = document.getElementById("greendiv")
//now add the condition
if (greenbox.style.display=="none")
{
greenbox.style.display="block";
}
else
{
greenbox.style.display="none";
}
});
// end for the green here -----------------------------------------------------
// start for the blue here -----------------------------------------------------
document.getElementById("button4blue").addEventListener("click", function() // made a function to call on onclicking
{
let bluebox = document.getElementById("bluediv")
//assigned a variable to it
//now add the condition
if (bluebox.style.display=="none")
{
bluebox.style.display="block";
}
else
{
bluebox.style.display="none";
}
});
// end for the blue here ----------------------------------------------------
// start for the red here ---------------------------------------------------
document.getElementById("button4red").addEventListener("click", function() // made a function to call on onclicking
{
let redbox = document.getElementById("reddiv")
if (redbox.style.display=="none")
{
redbox.style.display="block";
}
else
{
redbox.style.display="none";
}
});
</script>
</body>
</html>
Specifying a condition in payload sent in findByIdAndUpdate
Accounts model:
let accountsSchema = new mongoose.Schema({
posts:{
type: Array
}
});
const Post = mongoose.model("Account", postSchema);
controller in Posts microservice, which populates the posts array in the Accounts microservice:
let myAccountPosts = await axios.get(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/${userID}`)
.then((resp) => {
resp.data.message.map((account) =>{
account.posts.map((post) =>{
if(myUserPostID !== post._id){
//the following resets the entire posts array in the other microservice, consider resetting/deleting only that particular post
let deletePostFromAccountsMicroservice = axios.patch(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/update/${userID}`, {"posts.$[]": "abc"}, (err) =>{
if(err) return err;
});
}else{
console.log("no")
}
});
});
}).catch((err) =>{
console.log("err: ", err.message);
return err;
});
**Now I need to be able to update a single object in the array and not oveeride the whole array.**
This is what the response looks like:
{
posts:[{_id:'6290ed85716a08d29dab3aa5'}, { _id: '1234ed85716a08d29b35342' } ]
}
In the following line of code:
let deletePostFromAccountsMicroservice = axios.patch(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/update/${userID}`, {"posts.$[]": "abc"}, (err) =>{
if(err) return err;
});
I want the posts.$[] to target only the
object that has an _id that matches this condition (myUserPostID !== post._id)
How do achieve that?
Whats making my mouseover and react setState slow?
It feels like any sort of “click and drag” type of action I create feel kinda… well choppy. Like it’s studdering. I know when I console log the data is instant from the event, but the delays within the update to state are what makes it seem slower.
Here is a very simple example:
const TestMouseOver = () => {
const [pos, setPos] = useState();
const onMouseDown = (e) => {
setPos({
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop,
})
}
const onMouseMove = (e) => {
setPos({
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop,
})
}
return (
<div
onMouseDown={(event) => onMouseDown(event)}
onMouseMove={(event) => onMouseMove(event)}
onMouseUp={() => setPos(null)}
>
{pos && <MoveBox position={pos} />}
</div>
);
};
within MoveBox I take the pos and just set the divs absolute css as the position (styled-components). Nothing to fancy in there. It works but it’s laggy and slow.
Should I be attempted to build some sort of lerp or animation to go to last know coord to smooth out the position update?
Is there any way I can navigate to a link using options in html using JavaScript?
I created a list of options using html and placed a button beneath it…I want the user to select an option and when he clicks on the button,it redirects him to a different page…
Is there anyway that I can do this using JavaScript please?
Double slashes at the beginning of a URL?
I’m currently working on a chrome extension that allows me to to download the fonts files that have been used on a webpage.
As I was parsing the fonts for this site I ran into a strange edge case for one of the font URLs.
For the font Freddy the @font-face rule looks like this:
@font-face {
font-family: 'Freddy';
src: url("//cdn.shopify.com/s/files/1/0548/8708/8184/t/24/assets/freddy_regular_2-webfont.woff?v=147712666987587936441646682936") format("woff") ,
url("//cdn.shopify.com/s/files/1/0548/8708/8184/t/24/assets/Freddy_Regular_2.ttf?v=64870238297763773461646682938") format("truetype") ,
url("//cdn.shopify.com/s/files/1/0548/8708/8184/t/24/assets/freddy_regular_2-webfont.woff2?v=66678714148373221751646682937") format("woff2"); /* Safari, Android, iOS */}
This broke my script because the double backslash makes it an invalid URL (i.e. if I type it into the browser as is it will give me an error).
So I was wondering — what’s the purpose of the double slashes at the beginning of this URL? How does this actually retrieve the font if it seems to be an invalid URL?
