Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Thursday, October 12, 2023

Array.prototype.find() Vs Array.prototype.some() in TypeScript (and JavaScript)

 In TypeScript (and JavaScript), `Array.prototype.find()` and `Array.prototype.some()` are both array methods used for searching elements in an array, but they serve different purposes and have different behaviors:


1. `Array.prototype.find()`

   - Purpose: It is used to find the first element in an array that satisfies a given condition.

   - Return Value: Returns the first matching element found in the array or `undefined` if no matching element is found.

   - Example:

     ```typescript

     const numbers = [1, 2, 3, 4, 5];

     const evenNumber = numbers.find((num) => num % 2 === 0);

     // 'evenNumber' will be 2, which is the first even number in the array.

     ```


2. `Array.prototype.some()`

   - Purpose: It is used to check if at least one element in an array satisfies a given condition.

   - Return Value: Returns a boolean value (`true` or `false`) based on whether at least one element in the array matches the condition.

   - Example:

     ```typescript

     const numbers = [1, 2, 3, 4, 5];

     const hasEvenNumber = numbers.some((num) => num % 2 === 0);

     // 'hasEvenNumber' will be true because there is at least one even number in the array.

     ```


In summary, the main difference is in their purpose and return values:


- `find()` is used to retrieve the first element that matches a condition, and it returns that element or `undefined`.

- `some()` is used to check if at least one element in the array matches a condition, and it returns a boolean value (`true` or `false`).


You would choose between these methods based on your specific use case. If you need to find a specific element meeting a condition, use `find()`. If you want to check whether at least one element meets a condition, use `some()`.

Tuesday, May 2, 2023

what is the difference between @JsModule and @Javascript in vaadin ?

 @JsModule and @Javascript are both annotations in Vaadin that are used to import JavaScript files into your Java code. However, they are used in slightly different ways.

@JsModule is used to import an ES6 module that has been written in JavaScript or TypeScript. This annotation is used to declare the module name and path to the JavaScript file that contains the module. Vaadin automatically generates the necessary code to load the module at runtime and make it available in your Java code.

For example, if you have a JavaScript module called my-module.js in the frontend directory of your Vaadin project, you can import it into your Java code like this:

java
@JsModule("./frontend/my-module.js") public class MyView extends VerticalLayout { // ... }

@Javascript is used to import a regular JavaScript file that does not use the ES6 module syntax. This annotation is used to declare the path to the JavaScript file that you want to import. Unlike @JsModule, Vaadin does not generate any additional code for importing non-module JavaScript files.

For example, if you have a regular JavaScript file called my-script.js in the frontend directory of your Vaadin project, you can import it into your Java code like this:

java
@Javascript("./frontend/my-script.js") public class MyView extends VerticalLayout { // ... }

In summary, @JsModule is used to import ES6 modules, while @Javascript is used to import regular JavaScript files.

Friday, March 24, 2023

Redux createSlice vs createStore ?

 createSlice and createStore

are two different functions provided by the Redux library.

createStore is the core function of Redux that is used to create a Redux store, which is responsible for holding the entire state tree of the application. The store is created by passing a reducer function to createStore, which is responsible for specifying how the state tree is updated in response to actions.

On the other hand, createSlice is a utility function provided by the @reduxjs/toolkit package that simplifies the process of defining Redux reducers. It allows you to define a reducer function, initial state, and action creators all in one place. When you call createSlice, it generates a slice of the Redux store that contains the reducer function and action creators.

Using createSlice can help reduce the amount of boilerplate code required to define Redux reducers, and can make it easier to follow the principles of Redux by enforcing immutability and reducing the amount of manual bookkeeping required.

Here's an example of how you might use createStore and createSlice in a React TypeScript project:

import { configureStore, createSlice } from '@reduxjs/toolkit'; // Define the initial state interface AppState { count: number; } const initialState: AppState = { count: 0 }; // Define the reducer function and action creators using createSlice const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment(state) { state.count++; }, decrement(state) { state.count--; }, }, }); // Create the Redux store using configureStore const store = configureStore({ reducer: counterSlice.reducer, }); // Connect the React component to the store using the useSelector and useDispatch hooks import { useSelector, useDispatch } from 'react-redux'; function App() { const count = useSelector((state: AppState) => state.count); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch(counterSlice.actions.increment())}>Increment</button> <button onClick={() => dispatch(counterSlice.actions.decrement())}>Decrement</button> </div> ); } export default App;

In this example, we define the initial state of the application as an object with a count property. We then define the reducer function and action creators using createSlice, which generates a slice of the Redux store that contains the reducer function and action creators.

We create the Redux store using configureStore, and pass in the reducer function generated by counterSlice.reducer.

We then define a React component (App) that displays the current count and provides buttons to increment and decrement the count. We use the useSelector hook to select the count property from the Redux store, and the useDispatch hook to dispatch the increment and decrement actions when the buttons are clicked.

With this setup, when the user clicks the "Increment" button, the increment action is dispatched to the Redux store, which then calls the counterSlice.reducer function to update the .state of the counter slice. The updated state is then passed down to the App component as a prop, causing it to re-render with the updated count


which one is recommended for latest version react ?


Both createSlice and createStore are recommended for use with the latest version of React and Redux.

createSlice is a newer addition to the Redux library and provides a more concise and intuitive way to define reducers. It is recommended for use with small to medium-sized applications where the state is not too complex.

createStore, on the other hand, is the core function of Redux and is used to create the store that holds the entire state tree of the application. It is recommended for use in larger applications where the state is more complex and requires more advanced handling.

In general, it is recommended to use createSlice when possible as it simplifies the process of defining reducers and makes the code easier to read and maintain. However, createStore is still a crucial part of the Redux library and may be necessary for more advanced use cases.







Thursday, February 19, 2015

What is JSON ?

JSON stands for Javascript Object Notation.
Some descriptions are:

  • Format for sharing data
  • Derived from Javascript
  • Language independent (Originated with Js but availabe in many other language like PHP, C, Pearl, python)
  • An alternative to XML

Advantages:
  •  Leaner than XML
  • Easy to read
  •  Growing support in APIs
  • Natural format for Javascript
  • Implementation in many languages

Wednesday, January 14, 2015

adding jquery plugin in intrexx

As you already know you can directly write your javascript code in intrexx without any issue. But if  you have say a third-party javascript library or a jquery plugin that you want to add in intrexx you need to be aware of the following fact:
  1. Put a copy of your plugin in this directory:  \org\yourPortalName\external\htmlroot\include\custom\
  2. Open the following js file (\org\deinportal\external\htmlroot\include\custom\custom.js) and add the following:  Loader.loadJsFileOnDemand("include/custom/yourScriptName.js");
  3. Save everything and reload  your application
Enjoy it.

Friday, January 2, 2015

jquery NaN error

I have just written a small script today with jquery and come across this small error message.
inital code:

var1 += parseInt($(this).html());
var2 = parseFloat(age);

Solution

    var1 += parseInt( $(this).text(), 10 ) || 0;
  var2 = parseFloat(age) || 0;
 
Hope it helps. 

Saturday, December 20, 2014

Intrexx : transfer a parameter from one page to another using javascript

Hi, there are many ways to transfer paramters from between pages in Intrexx. This method I am going to present here is one them. I am not intending to write a complete solution with details but rather to point out some directives.

Javascript:


Page A:

- Dropdown list: value(Yes, NO)

- Button (onClick event: paramTransfer(this) )

Page B:
static text and select the option Only default language (such as for programming purposes).
[ $Request.get("rq_KNr") ]

More info regarding this topic can be found in documentations at united planet academy
Hope it helps and do not forget to drop a comment.

Monday, December 8, 2014

Session in javascript across pages.


 Some days back I had to implement a small feature in one of our company application. Had to think a while on how I could achieve that. Finally I end up solving the issue by smartly using Ajax and global variables. My intention here is not to give you code (at least you request it) but rather to present some ways around on solving such a matter. Taking the following point into consideration may help you dilute the situation:

  1.  Ajax: Asynchronous JavaScript and XML. AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
  2. Global variables
  3. The localStorage Object: The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year. e.g
  4. The sessionStorage Object: The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window. e.ghttp://www.w3schools.com/html/html5_webstorage.asp

Feel free to share your experience or feedback with us.