Formula: Multiply the percentage by the total value
Tag: javascript
Hello Guys,
Facing this issue and struggling to find the cause?, okay then lets direct jump in to the fix I found or more precisely mistake I found!
In my case I was wrapped the loading on controller in web.php route with single quotes!
Line of code causing this error:
Route::get('/book-readings/upload-photos', ['App\Http\Controllers\BookReadingController::class', 'uploadPhotos']);
Very carefully watch in above code code was wrapped in quotes: ‘App\Http\Controllers\BookReadingController::class’,
Controller should be loaded without single quotes;
And second important reason is it, this line should shall fall before the resource route if you have similar to this controller, in my case it was :
Route::resource('/book-readings', App\Http\Controllers\BookReadingController::class);
// this line was defined before the above route I wanted to work! (I am not sure why this line causing to stop showing the page :/)
Finally I make these changes so everything started working smoothly & all routes loading fine and up!.
// Upload Audio Files:
Route::get('/book-readings/upload-photos', [App\Http\Controllers\BookReadingController::class, 'showPhotos'])->name('book-readings.upload-photos');
Route::post('/book-readings/upload-photos', [App\Http\Controllers\BookReadingController::class, 'uploadPhotos']);
Route::delete('/book-readings/upload-photos/{id}', [App\Http\Controllers\BookReadingController::class, 'destroyPhoto']);
Route::resource('/book-readings', App\Http\Controllers\BookReadingController::class);
Hope this will give you a hint to point the issue you might come up like this mostly when we are new and learning and developing new things!
Happy Learnings
Hello,
This type error mostly get in scenario when you try to sort the readyonly data array.
For me this was occoured when I tried to sort the direct result from my GraphQL query response data like below:
const sortedData = data.bhangarwalas.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);
In above, data.bhangarwalas is graphql query response results which is readonly in nature as response.
To fix this issue the solution is quick fix for which I have too google to know the result!
Here is the quick solution:
const sortedData = [...data.bhangarwalas];
sortedData.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);
In code above, We need to clone or you in other words, copying the “data.bhangarwalas” into new array variable and then over that variable, we need to perform sorting operation, which results us right response.
Hope this help you to solve the quick error or to know what scenario this type of error is generated.
Thanks for reading.
Happy learning!
Hello,
The basic concept behind the event loop working in Javascript engine!
Event Loop is a mechanism in JavaScript that handles asynchronous tasks in a non-blocking way. When JavaScript code is executed, it is run inside an event loop, which continuously checks if there are any tasks to be executed in the queue. The event loop is responsible for running the tasks in the queue, and it does this in a specific order.
The Event Loop in JavaScript has two main components: the Call Stack and the Callback Queue. The Call Stack is responsible for keeping track of the execution of the synchronous code. When a function is called, it is added to the top of the call stack, and when the function returns, it is removed from the top of the call stack.
The Callback Queue, on the other hand, is responsible for keeping track of the asynchronous tasks. When an asynchronous task is completed, it is added to the Callback Queue. The event loop continuously checks the Callback Queue to see if there are any tasks that can be executed. If there is a task, it is moved to the Call Stack, where it is executed.
Microtasks and Macrotasks are two types of tasks in JavaScript that are executed by the event loop.
Microtasks are tasks that are executed immediately after the current task has completed. Microtasks are executed before the next rendering of the web page, which means that they have a higher priority than Macrotasks. Some examples of Microtasks include Promises, MutationObserver, and process.nextTick in Node.js.
Macrotasks, on the other hand, are tasks that are executed after all the Microtasks have been executed. Macrotasks include tasks such as setTimeout, setInterval, and I/O operations in Node.js.
In summary, the Event Loop in JavaScript is responsible for handling asynchronous tasks in a non-blocking way. The Event Loop has two main components, the Call Stack and the Callback Queue. Microtasks and Macrotasks are two types of tasks that are executed by the event loop, and they have different priorities. Microtasks are executed before Macrotasks and are used for tasks that need to be executed immediately after the current task has completed, while Macrotasks are used for tasks that can be executed at a later time.
Source: AI Interaction Channels
Happy Learning!
Hello,
This nice question and other below I have learned recently! Let see how its answered.
To identify the closed 5km range coordinates from a given set of coordinates, you need to first calculate the difference in latitude and longitude between the given coordinates and find the minimum and maximum values.
Here’s the basic formula:
Latitude range:
- min latitude = given latitude – (5 / 111.2)
- max latitude = given latitude + (5 / 111.2)
Longitude range:
- min longitude = given longitude – (5 / (111.2 * cos(given latitude)))
- max longitude = given longitude + (5 / (111.2 * cos(given latitude)))
Note: In the above formula, (5 / 111.2) is used to convert 5km to degrees. The value of 111.2 is the approximate number of km per degree of latitude. The value of (111.2 * cos(given latitude)) is used to convert 5km to degrees of longitude.
Once you have calculated the minimum and maximum values of latitude and longitude, you can create a bounding box by combining them. The coordinates within this bounding box would be considered as closed within a 5km range of the given coordinates.
Can you tell me more on last results?
Sure! The last results I mentioned are the coordinates of a bounding box that defines a closed area within a 5km range of a given set of coordinates.
A bounding box is a rectangular area that encloses a set of points or coordinates. In this case, the bounding box encloses the coordinates that are within a 5km range of the given coordinates. The minimum and maximum latitude and longitude values that were calculated earlier define the boundaries of this bounding box.
By combining the minimum and maximum latitude and longitude values, you get a rectangular area that encloses all the coordinates that are within a 5km range of the given coordinates. Any coordinate that lies within this rectangular area can be considered to be within a 5km range of the given coordinates.
This information can be useful in various applications, such as mapping, geolocation-based services, or location-based searches. For example, if you want to search for all the restaurants within a 5km range of a given location, you can use the bounding box coordinates to filter out the restaurants that are outside the 5km range.
Can you tell me more with example for bounding box calculations?
Sure, here’s an example of how you can calculate the bounding box coordinates for a given set of coordinates within a 5km range.
Let’s assume that the given coordinates are:
Latitude: 37.7749 Longitude: -122.4194
To calculate the bounding box coordinates:
- Calculate the minimum and maximum latitude:
- min latitude = 37.7749 – (5 / 111.2) = 37.7692
- max latitude = 37.7749 + (5 / 111.2) = 37.7807
- Calculate the minimum and maximum longitude:
- min longitude = -122.4194 – (5 / (111.2 * cos(37.7749))) = -122.4257
- max longitude = -122.4194 + (5 / (111.2 * cos(37.7749))) = -122.4131
So, the bounding box coordinates would be:
min latitude: 37.7692 min longitude: -122.4257 max latitude: 37.7807 max longitude: -122.4131
This means that any coordinate that lies within the rectangular area defined by these bounding box coordinates would be considered to be within a 5km range of the given coordinates (37.7749, -122.4194).
Well hope you understand from the given formulation and examples how can create a boundingbox for the range we need to search in for against our given co-ordinates, lets deep in further how we can implement and take this up with our Javascript Skills!
Nice, how I we can use this in Javascript?
Here’s an example of how you can calculate the bounding box coordinates for a given set of coordinates within a 5km range using JavaScript:
function getBoundingBox(lat, lng, distance) {
const RADIUS_OF_EARTH_KM = 6371;
const latRadian = lat * (Math.PI / 180);
const degLatKm = RADIUS_OF_EARTH_KM * Math.cos(latRadian);
const degLonKm = RADIUS_OF_EARTH_KM;
const latDegree = distance / degLatKm;
const lngDegree = distance / degLonKm;
return {
minLat: lat - latDegree,
minLng: lng - lngDegree,
maxLat: lat + latDegree,
maxLng: lng + lngDegree
};
}
const coordinates = { lat: 37.7749, lng: -122.4194 };
const boundingBox = getBoundingBox(coordinates.lat, coordinates.lng, 5);
console.log(boundingBox);
In this example, the getBoundingBox
function takes the latitude, longitude, and distance as input parameters. The distance is the radius of the bounding box and is specified in kilometers. The function first converts the latitude and longitude to radians and calculates the number of kilometers per degree of latitude and longitude. The minimum and maximum latitude and longitude values are then calculated using these values and the given distance. Finally, the bounding box coordinates are returned as an object.
Nice, How to I use the bounding box with real test case example?
Here’s an example of how you could use the bounding box coordinates with a real-world test case. Let’s say you have a list of restaurants and their coordinates, and you want to search for all the restaurants within a 5km range of a given location.
const restaurants = [
{ name: "Restaurant A", lat: 37.7820, lng: -122.4464 },
{ name: "Restaurant B", lat: 37.7696, lng: -122.4138 },
{ name: "Restaurant C", lat: 37.7816, lng: -122.4140 },
{ name: "Restaurant D", lat: 37.7711, lng: -122.4336 },
{ name: "Restaurant E", lat: 37.7634, lng: -122.4359 },
];
const searchLocation = { lat: 37.7749, lng: -122.4194 };
const searchRadius = 5;
const boundingBox = getBoundingBox(searchLocation.lat, searchLocation.lng, searchRadius);
const filteredRestaurants = restaurants.filter(restaurant => {
return (
restaurant.lat >= boundingBox.minLat &&
restaurant.lat <= boundingBox.maxLat &&
restaurant.lng >= boundingBox.minLng &&
restaurant.lng <= boundingBox.maxLng
);
});
console.log(filteredRestaurants);
In this example, the restaurants
array contains the list of restaurants and their coordinates. The searchLocation
object contains the location for which you want to search the restaurants. The searchRadius
specifies the radius of the search in kilometers.
The boundingBox
is calculated using the getBoundingBox
function, as shown in the previous example. The filteredRestaurants
array is then created by filtering the restaurants
array based on whether their coordinates fall within the bounding box or not. Finally, the filtered restaurants are logged to the console.
Hope this give us nice insight for the questions we have and need to develop as we develop advance things.
Source: Some AI Interaction Channels
Happy Learning!
Closures in JavaScript
A closure in JavaScript is a function that has access to variables in its outer scope, even after the outer function has returned. A closure is created when a function is defined inside another function and the inner function references variables in the outer function’s scope.
Closures allow you to preserve the state of a function’s variables even after the function has returned, and they can be used to create powerful and flexible functions that can be reused in different parts of your code.
Here’s a simple example of a closure in JavaScript:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
}
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
In this example, the outerFunction
returns the innerFunction
, which has access to the x
variable in its outer scope. When we call outerFunction(5)
, it returns the innerFunction
with x
set to 5, and we assign it to the add5
variable. When we later call add5(3)
, it returns the result of x + y
, which is 8.
Closures are an important concept in JavaScript, as they can be used to create functions that have private variables, to implement object-oriented concepts like classes and prototypes, and to manage state and data in complex applications.
Source: AI Interaction Channel
Happy Learning!
Filtering customers state array based on array of ids in javascscript/react.
const activeCustomerIdSet = [3,4,9];
//customers is array of customer data in my case its array value is bit different, just to note.
const filteredActiveCustomersIds = Array.from(activeCustomerIdSet) || [];
let nonActiveCustomers = [];
let filterCustomer = [...customers];
if (filteredActiveCustomersIds.length) {
for (let cid of filteredActiveCustomersIds) {
filterCustomer = filterCustomer?.filter(cust => {
if (+cust?.value?.id !== cid) {
return cust;
}
});
}
nonActiveCustomers = [...nonActiveCustomers,
filterCustomer];
}
console.log({ filteredActiveCustomersIds, customers, nonActiveCustomers });
Hope you find useful in your search!
Keeping it short simple and straight.
Happy coding!
Hello,
Here I would like to share with you a very handy and new innovative approach using ES6 Tag Literals template to ease of creating the base URL’s for use a single source of truth defined as library constants or utility code to refer as the single page application grows.
Let’s get hand dirty and mind free from hassle of maintaining and forming lines cluttered code and creating mess in many files as web application grows.
Hope you understand what I mean, developers get frustrated to follow the best practice as in tight project deadlines,
Heads up on I am currently using 2Factor.in endpoints in this post as I were using part of the project implementation, we will head in list out numbers as steps needs to follow for the quick implementation:
- We will save API key and API base URL in env file, (hope you are aware were it will lies in your project code, basically it lies at the core level of project director with named and with extension exactly, .env
SITE_2FACTORIN_API_BASE_URL=https://2factor.in/API/V1/
SITE_2FACTORIN_API_KEY=XXXXXX-dde0-23ec-XXXXXXXXXX
2. As I were using Nextjs, so I need to configure these env variables in next.config.js file to export it to the FE side contants(.js) file:
//next.config.js
module.exports = {
publicRuntimeConfig: {
SITE_2FACTORIN_API_BASE_URL: process.env.SITE_2FACTORIN_API_BASE_URL,
SITE_2FACTORIN_API_KEY: process.env.SITE_2FACTORIN_API_KEY,
},
};
3. Next we need to import publicRuntimeConfig object in our constants(.js) file
import { publicRuntimeConfig } from "./env.settings";
I am importing from .env.settings files which is actually using nextjs getConfig method to export publicRuntimeConfig variable, I am skipping that step to show here, once you search for docs on next/config you will get an idea what we are doing here.
4. Main part here it comes in contants.js file:
export const f2param1 = (param) => param || 1234657890;
export const f2param2 = (param) => param || "myTemplateName-OTP";
export function tagTemplate2FactorAPI(strings, param1, param2) {
const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';
let str0 = strings[0] || ""; // "That "
let str1 = strings[1] || ""; // " is a "
let str2 = strings[2] || ""; // "."
// We can even return a string built using a template literal
return `${prefixBaseUrl}${str0}${param1 || ''}${str1}${param2 || ''}${str2}`;
}
export const factor2API_Endpoint = {
CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN`,
SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN/${f2param2()}`,
SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${f2param1()}/${f2param2()}`,
CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};
console.log(factor2API_Endpoint.SEND_OTP_SMS);
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE);
console.log(factor2API_Endpoint.SEND_VERIFY_SMS);
This is how the final code looks, but there is a catch in this code, just need to handle of passing the params dynamically to the constants property of the object, otherwise with the fixed 2 params in same file would do the trick.
Will share once I got the way of passing dynamic params values to object property in template literal invocation line.
—— Here I found it the other approach —- Edited: 00:44 (after few mins of publishing this post after above approach shared 🙂 )
export function tagTemplate2FactorAPI(strings, ...keys) {
const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';
return (function (...values) {
let dict = values[values.length - 1] || {};
let result = [strings[0]];
keys.forEach(function (key, i) {
let value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
result.unshift(prefixBaseUrl); //added this line to prefix with base url path
return result.join('');
});
}
export const factor2API_Endpoint = {
CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN`,
SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN/${1}`,
SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${0}/${1}`,
CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};
console.log(factor2API_Endpoint.SEND_OTP_SMS(12311312, 'newTemplate-newOTP'));
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE(5656565, 'newTemplate-newOTP'));
console.log(factor2API_Endpoint.SEND_VERIFY_SMS(456646545, 'newTemplate-newOTP'));
Output log of the above code:
Solution, I found right after reading the basic guide on Tagged template on Mozilla documentation on Tagged Templates
Thanks for reading.
Happy Learning.