Thursday, July 18, 2024

Using Orderby ascending and Orderby descending to sort array javascript

Array.prototype.orderby=function()
{
  let self=this;
  let arr=[self[0]], i=1;
    for(;i<self.length; i++)
    {
      let index=arr.findIndex(f=>f > self[i]);
      arr.splice(index==-1?arr.length: index, 0, self[i]);
    }
  return arr;
}

Array.prototype.orderdescby=function()
{ 
 let self=this;
 let arr=[self[0]], i=1;
    for(;i<self.length; i++)
    {
        let index=arr.findIndex(f=>f < self[i]);
        arr.splice(index==-1?arr.length:index,0,self[i]);
    }
 return arr;
}

const points = [40, 100, 1, 500, 25, 107,0];
console.log(points.orderby())
console.log(points.orderdescby())

Wednesday, July 17, 2024

Javascript String extend for new function.

Javascript String extend for new function.
First Approch:
String.prototype.toArray=function(){
   let arr=[];
   for(let ch of this){
    arr.push(ch);
	}
	return arr;
}

let name="suresh";
console.log(name.toArray()); //output   [ 's', 'u', 'r', 'e', 's', 'h' ]

Second Approch:
String.prototype.toArray=function(){
	return this.split('');
}

let name="suresh";
console.log(name.toArray()); //output   [ 's', 'u', 'r', 'e', 's', 'h' ]

Difference between functions and methods in JavaScript:

 

  1. JavaScript Functions:

    • A function is a block of code designed to perform a specific task.
    • It can be defined using the function keyword, followed by a name and optional parameters.
    • The body of the function is enclosed in curly braces.
    • Functions are executed when something calls or invokes them.
    • Example:
      function addName(a, b) {
          return a + " " + b;
      }
      console.log(addName("Suresh", "Sharma")); // Output: Suresh Sharma
      
  2. JavaScript Methods:

    • A method is a function associated with an object.
    • It is a property of an object that contains a function definition.
    • Methods are functions stored as object properties.
    • They can be accessed using the following syntax: object.methodName().
    • Methods operate on the data contained in a class (i.e., the object it belongs to).
    • Example:
      let employee = {
          empname: "Suresh Sharma",
          department: "Software",
          details: function () {
              return this.empname + " works in "+ this.department +" Department.";    }};
                     console.log(employee.details()); // Output: "Suresh Sharma works in Software Department."

In summary:

  • A function can stand alone and be called directly by its name.
  • A method is a function associated with an object property.
  • Methods implicitly pass the object on which they were called.




Tuesday, July 16, 2024

Higher-Order Components (HOCs) and render props

  1. HOCs (Higher-Order Components):

    • Scenario: When you want to share cross-cutting concerns (such as data fetching, authentication, or logging) across multiple components.
    • Use Cases:
      • Data Fetching: Wrap components with an HOC that fetches data and provides it as props.
      • Authentication: HOCs can handle user authentication and authorization checks.
      • Logging and Analytics: Wrap components to log events or track user interactions.
    • Example:
      • React Router uses HOCs for route authentication and navigation.
  2. Render Props:

    • Scenario: When you need dynamic, flexible rendering behavior within a component.
    • Use Cases:
      • Conditional Rendering: Render different UI components based on state or props.
      • Customizable Behavior: Allow users of your component to inject their rendering logic.
      • Dynamic Children: Create components that can render different content dynamically.
    • Example:
      • Form libraries like Formik use render props to customize form rendering.
  3. Combining Both:

    • Sometimes, combining HOCs and render props provides maximum flexibility.
    • Scenario: When you want to share behavior (HOC) but allow customization (render props).
    • Use Cases:
      • Data Fetching with Custom Rendering: Use an HOC for data fetching and a render prop for custom rendering.
      • Composing Multiple Behaviors: Chain HOCs and render props together for complex components.
    • Example:
      • React Query library combines HOCs and render props for data fetching and caching.

In summary:

  • HOCs are great for cross-cutting concerns and reusable behavior.
  • Render props excel when you need dynamic rendering and customization.



Monday, July 15, 2024

Differences between forEach(), some(), and every() in JavaScript when working with arrays

forEach():
The forEach() method iterates over each element in an array and executes a provided function for each element. It does not return a new array; instead, it performs side effects (e.g., modifying elements, logging, etc.). Use forEach() when you want to perform an action on each element without creating a new array.
Example: JavaScript
const numbers = [1, 2, 3, 4];
numbers.forEach((num) => console.log(num));

some():
The some() method checks whether at least one element in the array satisfies a given condition (predicate). It returns true if any element passes the test; otherwise, it returns false. Use some() when you want to check if any element meets a specific condition.
Example: JavaScript
const strarr = ["method", "checks", "whether"];
const isFound = strarr.some((item) => item==="whether");
console.log(isFound); // true
const isNotFound = strarr.some((item) => item==="ram");
console.log(isNotFound); // false

every():
The every() method checks whether all elements in the array satisfy a given condition (predicate). It returns true if all elements pass the test; otherwise, it returns false. Use every() when you want to ensure that all elements meet a specific condition.
Example: JavaScript
const numbers = [1, 2, 3, 4];
const allPositive = numbers.every((num) => num > 0);
console.log(allPositive); // true

In summary:

Use forEach() for side effects (e.g., logging, modifying elements).
Use some() to check if any element meets a condition.
Use every() to ensure all elements satisfy a condition.

Saturday, July 13, 2024

Javascript Promise

JavaScript Promises: 
  Promise.all(): The Promise.all() method accepts an iterable (such as an array of promises) and returns a single promise. It resolves when all input promises have resolved successfully. If any of the input promises reject, the returned promise will also reject. Example: JavaScript
const promise1 = fetch('https://api.sureshsharma.net/data1');
const promise2 = fetch('https://api.sureshsharma.net/data2');

Promise.all([promise1, promise2])
  .then(([response1, response2]) => {
    // Handle both responses here
  })
  .catch((error) => {
    // Handle errors
  });
Promise.race(): The Promise.race() method takes an iterable of promises and returns a new promise. It resolves or rejects as soon as the first promise in the iterable resolves or rejects. Useful for scenarios like setting a timeout for an operation. Example: JavaScript
const timeoutPromise = new Promise((resolve, reject) => {
  setTimeout(() => reject('Timeout'), 5000);
});

const fetchDataPromise = fetch('https://api.sureshsharma.net/data');

Promise.race([timeoutPromise, fetchDataPromise])
  .then((response) => {
    // Handle the first resolved promise (either timeout or data)
  })
  .catch((error) => {
    // Handle errors (timeout or fetch failure)
  });
Promise.finally(): The finally() method allows you to specify a callback that runs regardless of whether the promise is resolved or rejected. Useful for cleanup tasks (e.g., closing resources, resetting state). Example: JavaScript
fetchDataPromise
  .then((data) => {
    // Process data
  })
  .catch((error) => {
    // Handle errors
  })
  .finally(() => {
    // Cleanup or final actions
  });
Promise.any(): The Promise.any() method returns a promise that resolves with the value of the first fulfilled promise in the iterable. If all promises reject, it rejects with an array of rejection reasons. Useful when you want to proceed with the first successful result. Example: JavaScript
const promises = [promise1, promise2, promise3];

Promise.any(promises)
  .then((result) => {
    // Handle the first successful response
  })
  .catch((errors) => {
    // Handle all rejections
  });
  

Thursday, July 11, 2024

The differences and use cases for find, filter, map, reduce, and from in JavaScript

The differences and use cases for find, filter, map, reduce, and from in JavaScript:

find:
Purpose: Finds the first element in an array that satisfies a given condition. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const found = numbers.find(item => item === 3);
console.log(found); // 3
When to Use: When you need to locate a specific element based on a condition.

filter:
Purpose: Creates a new array with elements that pass a specified test. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
When to Use: To filter out elements that don’t meet a certain condition.

map:
Purpose: Creates a new array by applying a function to each element in the original array. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
When to Use: When you want to transform each element in an array.

reduce:
Purpose: Reduces an array to a single value by applying a function to each element. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10
When to Use: For aggregating values (e.g., sum, product, concatenation).

from:
Purpose: Creates a new array from an iterable (e.g., string, Set, Map). Usage: JavaScript
const str = 'Hello';
const charArray = Array.from(str);
console.log(charArray); // ['H', 'e', 'l', 'l', 'o']
When to Use: When converting non-array iterables into arrays.
AJAX, asp, Asp.net, asp.net and sql server security, Asp.net IntemIndex, C#, Css, DataBinder.Eval, DataKeyNames, Datalist, Datapager, DataSet, DataTable, DropDownList, FindControl, gridview, JavaScript, jquery, Listview, Paging, Regex, RegularExpression, Repeater, Server side validation, Sql Server, timer, timercallback, Validation, XML, xmlnode, XPath