Category: javascript
Category Added in a WPeMatico Campaign
How to filter an array of objects by key
There are similar questions to this but I cannot find something to tackle this one exactly.
I have an Array that is shaped like this:
AllReviews: [
{0001: [
{Review: "In a Pickle", Notes: "Approved"},
{Review: "A Cat Nap", Notes: "Approved"},
{Review: "Flea market", Notes: "Approved"}
]
},
{0002: [
{Review: "Mouth-watering", Notes: "Approved"},
{Review: "Easy As Pie", Notes: "Approved"},
]
},
{0003: [
{Review: "Loved it", Notes: "Approved"},
{Review: "To sweet", Notes: "Rejected"}
]
}
]
I want to filter this Array so that it only returns the review for 002. I cannot figure out how to do it. My attempt was feeble:
AllReviews.value.filter((Review) => {
for (const [Key, Value] of Object.entries(Review)) {
return Review[Key] === 002 // Trying to say return the value (the array with reviews and notes) where the Key of the object matches what I want e.g. 002
}
})
My code is a nonsense of course and will not work.
Shift method in a singly linked list
I have this singly linked list:
class Node{
constructor(val){
this.val = val;
this.next = null;
}
}
class SinglyLinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
}
and this shift method:
shift(){
if(!this.head) return undefined;
var currentHead = this.head;
this.head = currentHead.next;
this.length--;
if(this.length === 0){
this.tail = null;
}
return currentHead;
}
The question is whether currentHead.next should be equal to null or not. I found several sources on the internet proposing the shift method from above, but I feel like the correct version is with currentHead.next = null.
Issue retrieving City/State/Zip line from block of text
I have a bunch of blocks of text that will contain address information such as:
Fake Name
Business name
60 N Address Ave.
San Jose, CA 95126
(555)255-5555
Email: [email protected]
I need to extract the line with the city/state/zip but it can be on a different line in every block of text. I have tried using regex but am not getting any returned results. Any help would be appreciated!
function findStateLine(text) {
const lines = text.split("n");
const regex = /b[A-Z]{2}b/;
for (let i = 0; i < lines.length; i++) {
if (regex.test(lines[i])) {
return lines[i].trim();
}
}
return null;
}
const stateLine = findStateLine(text);
console.log(stateLine);
Expect the line from above ‘San Jose, CA 95126’ but am not getting any results
Also tried ‘/[w ]+, w{2} d{5}/’ as well in regex const but did not get results as well.
How to run react-leaflet hook only when button is clicked
I am trying to implement some simple movement controls on a react-leaflet map to allow “flying” to a set of predefined coordinates after pressing a button.
I’m aware that the Map instance created by react-leaflet can be accessed by child components and so I’m utilising the useMap() hook in a child component to achieve this as follows in NavigateToMarker.jsx:
import { useMap } from "react-leaflet";
export default function NavigateToMarker({position}) {
const map = useMap();
map.flyTo(position, 13)
return null
}
MainMap.jsx looks like this:
import NavigateToMarker from './NavigateToMarker';
export default function MainMap() {
const [position, setPosition] = React.useState([51.607642, -0.129303])
const handleClick = (position) => {
setPosition(position)
}
<MapContainer>
<TileLayer />
<GeoJSON data={geoJsonData} />
<NavigateToMarker position={position} />
</MapContainer>
<Button onClick={() => handleClick([52.309611, -0.139303])}>Fly To Position</Button>
}
The button does fly to the specified position but my problem is that the NavigateToMarker code is ran every time the MainMap component renders.
I’ve tried including the button inside NavigateToMarker but because this component is then placed within a MapContainer component, the buttons don’t show and I’m not sure how easily I’d be able to apply an CSS gridding and styling with this method.
Is there a way to ensure that NavigateToMarker is only invoked when the button in MainMap.jsx is clicked?
issue related to focus in tizen, using javascript
i m writing a code in JS. The issue i facing is that when my focus is on menu bar and i m pressing right key focus is skipping first item_row i.e. from menu bar it goes to row_item_1_1
skipping row_item_1_0 and from menu to item_row_2_1 skipping item_row_2_0 and so on. how can i resolve this issue.My code is as follows:
case "ArrowRight": // Right button
if (
$(".sidebar-container").hasClass("toggle_menu") &&
$("[id^=menu_]").is(":focus")
) {
if ($(".profile_container").hasClass("active")) {
var $logoutButton = $("#logout-button");
if ($logoutButton.length) {
console.log("element found with id #logout-button");
$logoutButton.focus();
}
} else SN.focus(`#${first_page_focused_element}`);
}
e.preventDefault();
break;
I tried asking catgpt but it didn’t help. i want that when i use right key my focus doesn’t skip first element of the rows.
Issue with Date Calculation
If a transaction is set for the 31st then the calculate last day etc. for things like Feburary allow for it to be set to the 28th or 29th depending on if it’s a leap year.
Curently I don’t get Feburary in the Array of transactions submitted, which I assume is caused by some miscalculation. Can someone help?
import axios from 'axios';
import './AddTransactionModals.css'; // Add your custom styles here
interface AddTransactionModalProps {
isOpen: boolean;
onClose: () => void;
}
export const AddTransactionModal: React.FC<AddTransactionModalProps> = ({ isOpen, onClose }) => {
const [formData, setFormData] = useState({
type: 'Expense',
title: '',
amount: '',
date: '',
reocurrance: 'one-time',
enddate: '',
creditTransId: '',
notes: '',
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const getLastDayOfMonth = (year: number, month: number) => {
return new Date(year, month + 1, 0).getDate();
};
const adjustToLastDayOfMonth = (date: Date) => {
const lastDay = getLastDayOfMonth(date.getFullYear(), date.getMonth());
const adjustedDate = new Date(date);
adjustedDate.setDate(Math.min(date.getDate(), lastDay -1));
return adjustedDate;
};
const calculateRecurringDates = (startDate: Date, recurrence: string, endDate: Date) => {
const dates: Date[] = [];
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
let adjustedDate = adjustToLastDayOfMonth(currentDate);
if (adjustedDate > endDate) break;
dates.push(new Date(adjustedDate));
switch (recurrence) {
case 'weekly':
currentDate.setDate(currentDate.getDate() + 7);
break;
case 'bi-weekly':
currentDate.setDate(currentDate.getDate() + 14);
break;
case 'monthly':
// Increment month and adjust day
currentDate.setMonth(currentDate.getMonth() + 1);
currentDate.setDate(startDate.getDate());
currentDate = adjustToLastDayOfMonth(currentDate);
break;
case 'bi-monthly':
// Increment month by 2 and adjust day
currentDate.setMonth(currentDate.getMonth() + 2);
currentDate.setDate(startDate.getDate());
currentDate = adjustToLastDayOfMonth(currentDate);
break;
case 'yearly':
// Increment year and adjust day
currentDate.setFullYear(currentDate.getFullYear() + 1);
currentDate.setDate(startDate.getDate());
currentDate = adjustToLastDayOfMonth(currentDate);
break;
default:
break;
}
}
return dates;
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const endOfYear = new Date(new Date().getFullYear(), 11, 31); // End of current year
let endDate = formData.enddate ? new Date(formData.enddate) : endOfYear;
const startDate = new Date(formData.date);
const recurrenceDates = formData.reocurrance !== 'one-time'
? calculateRecurringDates(startDate, formData.reocurrance, endDate)
: [startDate];
try {
const requests = recurrenceDates.map(date => {
const transactionData = {
...formData,
date: date.toISOString().split('T')[0], // Format as YYYY-MM-DD
};
return axios.post('http://localhost:5000/api/transactions', transactionData, {
headers: {
'Content-Type': 'application/json',
},
});
});
await Promise.all(requests);
console.log('Transactions added successfully');
onClose(); // Close the modal after submission
} catch (error) {
console.error('Error adding transaction:', error);
}
};
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div className="modal-content">
<button className="modal-close" onClick={onClose}>
×
</button>
<h2>Add Transaction</h2>
<form onSubmit={handleSubmit}>
<label>
Title:
<input
type="text"
name="title"
value={formData.title}
onChange={handleChange}
required
/>
</label>
<label>
Type:
<select
name="type"
value={formData.type}
onChange={handleChange}
>
<option value="Expense">Expense</option>
<option value="Payday">Payday</option>
<option value="Credit Card Payment">Credit Card Payment</option>
<option value="Placeholder">Placeholder</option>
</select>
</label>
<label>
Amount:
<input
type="number"
name="amount"
value={formData.amount}
onChange={handleChange}
required
/>
</label>
<label>
Date:
<input
type="date"
name="date"
value={formData.date}
onChange={handleChange}
required
/>
</label>
<label>
Recurrence:
<select
name="reocurrance"
value={formData.reocurrance}
onChange={handleChange}
>
<option value="one-time">one-time</option>
<option value="weekly">weekly</option>
<option value="bi-weekly">bi-weekly</option>
<option value="monthly">monthly</option>
<option value="bi-monthly">bi-monthly</option>
<option value="yearly">yearly</option>
</select>
</label>
{formData.reocurrance !== 'one-time' && (
<label>
End Date:
<input
type="date"
name="enddate"
value={formData.enddate}
onChange={handleChange}
/>
</label>
)}
{formData.reocurrance === 'one-time' && (
<label>
End Date:
<input
type="date"
name="enddate"
value={formData.enddate}
disabled
/>
</label>
)}
<label>
Notes:
<textarea
name="notes"
value={formData.notes}
onChange={handleChange}
/>
</label>
<label>
Credit Transaction ID:
<input
type="number"
name="creditTransId"
value={formData.creditTransId}
onChange={handleChange}
/>
</label>
<button type="submit">Add Transaction</button>
</form>
</div>
</div>
);
};
`
Blank page when protecting route with react router
I have followed several guides and questions on stack overflow with no luck.
I want to set up protected routes, so going to example /highscores would redirect user to /login if not signed in.
Currently if not signed in and going to /highscores, i just get a blank page, if im signed in and go to highscores i get redirected to login..
The pages and auth token works with value in other parts of the system. But in none of the scenarios does it even print “No AUTHH” or “GOT AUTHHH”
“react-router-dom”: “^6.8.0”,
“react”: “^18.2.0”
In my index.jsx
export const AuthContext = createContext("");
const [authToken, setAuthToken] = useState("");
useEffect(() => {
let token = Cookies.get("authToken")
setAuthToken(token);
/../
return (
<TimerProvider>
<AuthContext.Provider value={{authToken, setAuthToken}}>
<BrowserRouter>
<FixedLayout>
<Routes>
<Route
element={<PrivateRoute/>}>
<Route path="/highscores" element={<HighScoresPage/>}/>
</Route>
</Routes>
</FixedLayout>
</BrowserRouter>
</AuthContext.Provider>
</TimerProvider> )
and my PrivateRoute.jsx
import { AuthContext } from "./index";
import React, {useContext} from 'react'
import {Navigate} from "react-router-dom"
const PrivateRoute = ({children}) => {
const { authToken } = useContext(AuthContext);
if(!authToken) {
console.log("No AUTHH")
return <Navigate to="/login" />
}
console.log("GOT AUTHHH")
return children
};
export default PrivateRoute;
Dynamically check (and change?) audio file codec
Hey all I have a web app where users can upload audio files like mp3’s, wavs and m4a’s.
I’m simply using the default html audio player to render the audio.
A while back I started noticing that a sporadic few of the audio players were greyed out.
I went into my supabase backend to open the actual audio file and found that I was able to play the audio file
when I downloaded it to my PC.
Upon reading this thread (Why is this specific m4a audio file not playing on the <audio> component, but any other one will?)
it looks like the issue is the codec with some .m4a files.
Some m4a files are using the AAC (widely supported) codec and some are not.
Currently I have JS code that
- grabs the file blob
- checks if the upload name contains mp3, wav or m4a
- uploads the blob to supabase
in between 2 and 3 I’d like to check that the codec of the blob is AAC and if possible change the codec (??)
I’ve asked CGPT for a solution but it point sme to FFMPEG and from reading the docs it looks like FFMPEG core is about 30MB to load…
(https://ffmpegwasm.netlify.app/docs/getting-started/usage/)
This seems like a lot to me – granted most of the app will have already been loaded by the time a user gets to this flow.
I just wanted to reach out and see if anyone has figured out a better solution
JS – required lib returns a constructor – how to test?
There is this NPM lib: https://www.npmjs.com/package/clamscan
It is being used like this according to the docs:
const NodeClam = require('clamscan');
const ClamScan = new NodeClam().init(options);
ClamScan.then(async clamscan => {
const {isInfected, file, viruses} = await clamscan.isInfected('./some/file');
});
how are you supposed to test this? I have never encountered a constructor being returned from a require.
Object Oriented JavaScript: relationship between objects [closed]
I have made some progress with the syntax of objects in JavaScript but I am not clear about their use in the overall context of an application such as a shopping cart. I have read quite a lot on MDN’s website on OOP for JavaScript but seem to only have learnt details of implementation and not the overall structure of a program.
If I made a class for products then every instance would be a single product but would it be sensible to have lots of instances with different names eg product-1, product-2 etc. to me that seems worse than just having an array of products where each product is another array containing name, description, price etc. Does every instance have to have a name?
Also how would I iterate over all instances of a class? The only way I can think of is to add every instance, when it is constructed, to an array or object and then iterate that.
Would it be sensible in OOP to have a class representing the store which would contain all the instances of the product class which represent each product? Then I could have classes for orders, customers etc. Does this make sense?
I have seen a huge amount of material when I google this but always get bogged down in syntax when I start to read it. Any advice on this or pointers to really good literature on the subject or examples would be very useful.
How To Call logout api, while refreshing or reloading page
How To Call logout api, while refreshing or reloading page
we called logout API on window.onbeforeunload event listener, So Logout API Called on clicking the cancel button of confirmation window.
Try to call logout API on window.onunload event listener, but no luck.
Nextjs – Get exported variable from page in a component
I have started to dig deeper in my application and I want to know if there is a way to get an exported variable from a page.js/ts/tsx from a component.
My idea is to have a menu component that will scan all page.js within the app directory (i am using nextjs) and look in the files for an exported constant, for example:
page.js
export const ToMenu = {
title: 'Home',
icon: null,
parent: null
}
export default function HomePage() {.......
Then in my menu components I will search for all variables ToMenu and preapare an array to update my menu automatically.
Not sure if this is possible but I got the idea from the nextjs export const metadata that will tell the nextjs where to place that specific information! maybe this way I can build the menu automatically because sometimes I build new pages and forgot to put them in the existing menu
Issue with Selecting Location in React Native Maps
I am using react-native-maps to let users select a location from the map. However, I have to click multiple times before the location gets selected, and the marker updates its position. Is this a performance issue, or is there a problem with my code?
Expected Behavior:
When a user clicks on a location on the map, the marker should immediately move to the new location, and the location name should be insertedd to the selectedLocation state.
Here’s my component:
const LocationScreen = () => {
const [selectedLocation, setSelectedLocation] = useState('');
const [markerCoordinates, setMarkerCoordinates] = useState({ latitude: 24.4539, longitude: 54.3773 });
const API_KEY = '893*********************';
const handleMapPress = async (event) => {
const { latitude, longitude } = event.nativeEvent.coordinate;
try {
const response = await axios.get(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=${API_KEY}`);
const components = response.data.results[0].components;
const location =
components.town ||
components.city ||
components.village ||
components.hamlet ||
components.locality ||
components.country;
if (location) {
setSelectedLocation(location);
setMarkerCoordinates({ latitude, longitude });
} else {
setSelectedLocation('Unknown location');
}
} catch (error) {
console.error("Error fetching location data: ", error);
}
};
return (
<View style={styles.container}>
<StatusBar
backgroundColor="transparent"
barStyle="dark-content"
translucent={true}
/>
<SafeAreaView style={styles.form}>
<View style={styles.head}>
<BackArrow /> {/* Assuming BackArrow is a valid component */}
<Text style={styles.title}>Location</Text>
</View>
<MapView
style={{ width: '100%', height: "100%" }}
initialRegion={{
latitude: 24.4539,
longitude: 54.3773,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
onPress={handleMapPress}
>
{markerCoordinates && (
<Marker
coordinate={markerCoordinates}
title={selectedLocation}
/>
)}
</MapView>
{selectedLocation && (
<View style={styles.selectedLocationContainer}>
<Text style={styles.selectedLocationText}>Selected Location: {selectedLocation}</Text>
</View>
)}
</SafeAreaView>
</View>
);
};
export default LocationScreen;
Jquery $(“body”) not selecting whole page
I have a page that I need to show a loading gif. The problem is when I select whole page with $(“body”) to disable editing fields, the elements that only reachable by scrolling down, in the other words, the area that is not visible is not selecting so they are still clickable when loading gif is active. Even clicking the html element on inspector tab is not selecting the whole page but only visiable area. How can I select whole page?
my code:
request: function (form, args, notice, callback, callback_err, prevent_refresh_table) {
var loader_container = null;
if(form){
if(($.type(form) == "string") && (form == "confirmation" || form == "settings")){
loader_container = $(".content-page");
}
else if($(form).find(".ajax-loader").length > 0) {
loader_container = $(form);
console.log("form")
}
else {
loader_container = $(form).closest("#myModal");
console.log("mymodal")
}
// If ajax loader does not exist show extensive loader
if(loader_container.find(".ajax-loader").length <= 0) {
loader_container = $("body");
console.log("body")
}
loader_container.find(".ajax-loader").show();
}
