menu

Search By Label

The test() method of JavaScript executes a search for a match between a regular expression and a specified string. If the match is found, it will return true. Otherwise, it will return false.

export const displayRoute = (route: string, t: (key: string) => string): string => {  
  const accountDetailRegex = /^\/accounts\/[0-9a-fA-F-]{36}$/;
if (accountDetailRegex.test(route)) return t('accountDetails'); };

In this example, we received a route and parsed it in regex to test() to verify whether it matched the possible characters of the routes. 

You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.

var str = "P001.M003.PO888393"; 
var res = str.replace(/^[^\.]*\./, '');
console.log(res);

Output: 
#=> M003.PO888393

If you need to create an initial array with default values and specific length you can use:
arr = new Array(3).fill(0)
Single-Threaded Execution: JavaScript operates on a single thread, meaning it executes one task at a time using the call stack, where functions are processed sequentially.

Call Stack: Picture the call stack as a stack of plates. Each time a function is invoked, a new plate (function) is added to the stack. Once a function completes, the plate is removed.

Web APIs: Asynchronous tasks like setTimeout, DOM events, and HTTP requests are managed by the browser’s Web APIs, operating outside the call stack.

Callback Queue: After an asynchronous task finishes, its callback is placed in the callback queue, which waits for the call stack to clear before moving forward.

Event Loop: The event loop constantly monitors the call stack. When it's empty, the loop pushes the next callback from the queue onto the stack.

Microtasks Queue: Tasks like promises are placed in a microtasks queue, which has higher priority than the callback queue. The event loop checks the microtasks queue first to ensure critical tasks are handled immediately.

Priority Handling: To sum up, the event loop prioritizes microtasks before handling other callbacks, ensuring efficient execution.
Shallow copy
A shallow copy duplicates only the top-level properties. If those properties are references (like objects or arrays), the copy will reference the same objects.
let original = { a: 1, b: { c: 2 } }
let copy = { ...original }
copy.b.c = 3 // Changes "original.b.c"
When to use:
- Small objects with primitive data types.
- Situations where performance is critical.
- Cases where changes to nested objects should reflect in all copies.

Deep copy
A deep copy creates a complete clone of the original object, duplicating all nested objects and arrays.
let original = { a: 1, b: { c: 2 } }
let copy = JSON.parse(JSON.stringify(original));
copy.b.c = 3 // The "original.b.c" remains 2
When to use:
- Complex objects with nested structures.
- Scenarios where complete independence from the original object is needed.
- Preventing unintended side-effects from shared references.
You can print the full object with all the child nodes of an object using:
console.dir(body, { depth: null });
It is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.

//example
const double = (x) => x * 2;
const square = (x) => x * x;

var output1 = double(2);
var output2 = square(output1);
console.log(output2);

var output_final = square(double(2));
console.log(output_final);
process.nextTick() is a function in Node.js designed to schedule a callback function to be invoked in the next iteration of the event loop. 

It allows a callback to be executed immediately after the current operation but before the event loop continues. This makes it useful for ensuring that certain tasks, especially related to the execution context or I/O, are deferred until the next tick of the event loop. It is often used to break down large asynchronous operations into smaller, more manageable chunks.
Isomorphic JavaScript works in the context of a single-page application (SPA). In a typical SPA, most of the application logic, including routing, is encapsulated in a bundled JavaScript file that is sent to the client. While this frees up the server, as it does not have to handle so many requests, it also makes the initial load slow for the client, as the entire application needs to be sent over to the client.

With Isomorphic JavaScript, when a client web page is first requested from the server, the view of the page is generated on the server, similar to server-side dynamic web pages, and sent over to the client. The client can then render the view immediately. After the initial view is rendered, the complete SPA is downloaded in the background, and subsequent actions are handled client-side.

If you want to validate a field in js for example a password field, you can use the regex, is a sequence of characters that forms a search pattern
I have the pwdField
and my  const to test is const validPwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])([A-Za-z\d$@$!%*?&]|[^ ]){8,}$/;
  1. Min 8 characters
  2. at least one  uppercase or lowercase letter
  3. contains $@$!%*?&
You can use the test method to validate the field.
Example:
    const getPwdAndValidate = (pwdField, pwdField2) => {
    const validPwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])([A-Za-z\d$@$!%*?&]|[^ ]){8,}$/;
        if (pwdField === pwdField2 && validPwd.test(pwdField) && pwdField.length >= 8) {
            return pwdField;
        } else {
            return null;
        }
    };

 This method is used to create a new Map data structure. A Map is a built-in data structure in JavaScript that allows you to store key-value pairs and provides various methods for working with these pairs. Here's how you can use "new Map()" to create a new Map:
 
Example:

const myMap = new Map();myMap.set('name', 'John'); 
myMap.set('age', 30);console.log(myMap.get('name')); // Output: 'John' 
console.log(myMap.get('age')); // Output: 30
Javascript supports currency formatting without any library. 

Example:

const number = 123456.789;console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number)); 
// Expected output: "123.456,79 €"// The Japanese yen doesn't use a minor unit 
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)); 
// Expected output: "¥123,457"// Limit to three significant digits 
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number)); 
// Expected output: "1,23,000"

The first parameter used is an Intl namespace internationalization.
In JavaScript, console.time is a method that helps you measure the time it takes for a specific block of code to execute. It's like a stopwatch for your code. 

Example:

// Start the timer 
console.time('myTimer');// Simulate a time-consuming operation 
for (let i = 0; i < 1000000; i++) { 
 // Some code here 
}// Stop the timer and display the elapsed time in milliseconds 
console.timeEnd('myTimer');
 
So, when you run this code, you'll see something like: "myTimer: 23.789ms"
Is a JavaScript method used for displaying an interactive list of the properties of a specified JavaScript object. It is particularly useful for examining the structure and contents of complex objects, such as DOM elements or custom JavaScript objects. 

Here's how `console.dir()` works with an example:

const person = { 
 firstName: "John", 
 lastName: "Doe", 
 age: 30, 
 address: { 
 street: "123 Main St", 
 city: "Anytown", 
 state: "CA", 
 zip: "12345", 
 }, 
};console.dir(person);/* output: 
Object 
 age: 30 
 address: Object 
 city: "Anytown" 
 state: "CA" 
 street: "123 Main St" 
 zip: "12345" 
 firstName: "John" 
 lastName: "Doe" 
*/ 

In JavaScript, a generator is a special type of function that allows you to pause and resume its execution. Generators are defined using the function* syntax, and they are capable of producing a sequence of values lazily, one at a time. They are particularly useful for working with asynchronous code and creating iterable objects. 
 
Let's assume you have a web application that fetches a large dataset of users from a remote API. Loading all users at once would be inefficient and slow. Instead, you can use a generator to paginate through the data, fetching a limited number of users at a time as needed.

Example:

async function* fetchUsers() { 
 let page = 1; 
 const perPage = 10; // Number of users per page

while (true) { const response = await fetch(`https://api.example.com/users?page=${page}&per_page=${perPage}`); const users = await response.json();
if (users.length === 0) { // No more users to fetch break; }
for (const user of users) { yield user; }
page++; } }
// Usage: 
const userGenerator = fetchUsers();(async () => { 
 for await (const user of userGenerator) { 
 console.log(`User: ${user.name}, Email: ${user.email}`); 
 } 
})();