Find Duplicate String and Letters from a Given string – Java(Collections)

**



Program to find Duplicate String and Letters from a Given string – Java(Collections)

**

package Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Program1 

    public static void findDuplicateWords(String str) 
        // 1. Split the String - String Array formation
        String[] s = str.split(" ");

        // 2. Crate a HashMap to get key-value pair
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (String temp : s) 
            if (map.get(temp) != null) 
                map.put(temp, map.get(temp) + 1);
             else
                map.put(temp, 1);
        

        // 3. To find duplicate words from keyValue set
        Set<Map.Entry<String, Integer>> data = map.entrySet();
        for (Map.Entry<String, Integer> dup : data) 
            if (dup.getValue() > 1)
                System.out.println("The word : '" + dup.getKey() + "' appeared - " + dup.getValue() + " times");

        
    

    public static void findDuplicateLetters(String str) 
        //1.Remove whitespaces
        str = str.replace(" ", "");

        //2.Convert to Lower case all letters
        str=str.toLowerCase();

        //3. create Hash map to get key-value pair
        HashMap<Character, Integer> hmap = new HashMap<>();

        for (int i = 0; i < str.length(); i++) 
            char ch = str.charAt(i);
            if (hmap.get(ch) != null) 
                hmap.put(ch, hmap.get(ch) + 1);
             else
                hmap.put(ch, 1);
        
        Set<Map.Entry<Character, Integer>> data = hmap.entrySet();
        for (Map.Entry<Character, Integer> dup : data) 
            if (dup.getValue() > 1)
                System.out.println("The word : '" + dup.getKey() + "' appeared - " + dup.getValue() + " times");
        
    

    public static void main(String[] args) 
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the Stirng");

        String str = input.nextLine();

        findDuplicateWords(str);
        findDuplicateLetters(str);

    



Source link

10 Commandments for Programmers

Do your best to follow these 10 commandments 👇🏽

  1. Make Googling a habit or thou shall make very little progress in programming.

  2. If it works, do not touch it unless you know what you are doing.

  3. JavaScript might be well spoken of but it is not your friend.

  4. Never debug in production.

  5. Argue not about programming languages on Twitter.

  6. Do not claim you know CSS. It is a lie, we all know.

  7. Eat in the morning before you start programming. Otherwise you may not eat again.

  8. No matter how sure you are, always clear your browser cache and try again.

  9. It is easier to stay up till 6:00 AM than to wake up at 6:00 AM. Be discipline with your sleep cycle.

  10. Always hide your wifi network SSID. There are others who are more dangerous than you think.

Did you enjoy these commandments? Do you want to write yours up or contribute to these ones, feel free & hit me up on Twitter: @xSavitar.




Source link

What is Module?

A module is a file containing Python definitions and statements which we can use in other Python programs.
A module is simply a “Python file” which contains code(functions, classes,lists etc) we can reuse in multiple Python programs.

Modules in Python can be of two types:

Built-in Modules.
User-defined Modules.

Modules allows us to use the functionality we need when we need it, and it keeps our code cleaner.

The functions we import as part of a module stays in their own namespace.(A namespace is simply a space within which all names are different from each other). The same name can be reused in different namespaces but two objects can’t have the same name within a single namespace.

For example, Many cities have a street called “Main Street”,
It is okay if ‘different’ cities have that ‘same’ street name but it’s very confusing if two streets in the same city have that same name!

Another example is the folder organization of file systems. One can have a file called “todo” in her work folder as well as her personal folder, but she knows which is which because of the folder it’s in; each folder has its own namespace for files.

One important note, human names are not part of a namespace that applies uniqueness; that’s why governments have invented unique identifiers to assign to people, like passport numbers.

In order to use Python modules, we have to import them into a Python program.

1)If we import morecode in a code, that imports everything in morecode.py. To invoke a function f1 that is defined in morecode.py, we can write morecode.f1().

morecode.f1

Note that we have to explicitly mention morecode again, to specify that we want the f1 function from the morecode namespace.If we just write f1(), python will look for an f1 that was defined in the current file, rather than in morecode.py.

2)We can also give the imported module an alias (a different name, just for when we use it in our program). For example, after executing import morecode as mc,
we would invoke f1 as mc.f1(). We have now given the morecode module the alias mc. Programmers often do this to make code easier to type.

3)A third possibility for importing occurs when we only want to import SOME of the functionality from a module and we want to make those objects be part of the current module’s namespace.
For example, we could write from morecode import f1. Then we could invoke f1 without referencing morecode again: f1().


Source link

A Swiss Army Knife for JS Variables: Var or Let or Const?



Introduction

Yet another blog explaining Var, Let and Const but I promise this is the only one you need.

ECMASCRIPT2015, also known as ES6 introduced a lot of awesome features. One of the features was the addition of let and const for declaring variables. Previously developers used var for variable declaration, so what was the need of bringing new ones?

If you don’t know what let and const brings to the table and how are they different from each other, this blog post is for you. I will compare them based on usage, scope, and hoisting.



Var

Before the introduction of ES6, the only way to define variables in JavaScript was to use the var keyword. For many years, it worked fine, however var differs from other programming languages in terms of variable scoping leading to unwanted bugs that are hard to track.

The below code example demonstrates the declaration of a variable with the var keyword:

var declaredWithVar = "welcome to the blog";
console.log(declaredWithVar);  //welcome to the blog



Scope

The Scope refers to the present context of code, which decides the accessibility of the variables.
The scope is of two types Global and Local:

  • Variables that are declared outside of a block are known as Global variables.
  • Variables that are declared inside of a block are known as Local variables.

The variables declared with var are globally scoped when declared outside a function. Any variable declared with var outside of a function block is accessible across the whole window.

var is a function scoped when it is declared within a function which means that it is accessible within that function only.

Look at the example below to understand further:

var globalScopedVar = "declared globally"

function varScopeCheck()
  var scopingOfVarInFunc = "declared inside function"
  console.log(scopingOfVarInFunc)


console.log(scopingOfVarInFunc) //Uncaught ReferenceError: scopingOfVarInFunc is not defined
console.log(varScopeCheck()) //declared inside function
console.log(globalScopedVar) //declared globally

As you can see, we cannot access scopingOfVarInFunc outside of the function as the variable is locally scoped but we can access the globalScopedVar as it is globally scoped.

var can also be redeclared and updated.

This means the value of the variable can be updated by reinitializing and the variable declared with the var keyword can be declared again and again with the same or different values.

Look at the example below to understand further:

var declaredVar = "First time"
var updatedVar = "Old value"

var declaredVar = "Second time"
updatedVar = "New value"

console.log(declaredVar) // Second Time
console.log(updatedVar) // New value



Hoisting

Hoisting is the process by which the interpreter allocates memory for variable and function declarations prior to executing the code. This allows us to use a variable before it has been declared and initialized.

For example:

 console.log(hoistedVar); //undefined
 var hoistedVar = "I'll be hoisted"

why undefined? why not defined error?
var variables are hoisted to the top of the scope and initialized with the value undefined.



Problem with var

var nameUsingVar = "Michael"
if(true)
  var nameUsingVar = 'Mike instead'

console.log(nameUsingVar) // Mike instead

In the above code example, global scoped nameUsingVar is replaced by the block-scoped nameUsingVar and we get the unexcepted value. Well, it is not a problem if it’s intentional but imagine managing your variables after 1000s of lines of code. This will become tricky to work with and cause a lot of bugs in your code.

That is why let and const were introduced and widely used.



Let

let came as an improvement over var by being block-scoped which solves the problem discussed above.

The below code example demonstrates the declaration of a variable with the let keyword:

let declaredWithLet = "I am preferred over var";
console.log(declaredWithLet);  //I am preferred over var



Scope

Variables declared with let are block-scoped which means that a variable declared in a block with let is only available for use within that block. Variables declared outside blocks are global scoped.

Let’s understand it with an example:

let globalScopedLet = "declared globally"

function letScopeCheck()
  let scopingOfLetInFunc = "declared inside function"
  console.log(scopingOfLetInFunc)


console.log(scopingOfLetInFunc) //Uncaught ReferenceError: scopingOfLetInFunc is not defined
console.log(letScopeCheck()) //declared inside function
console.log(globalScopedLet) //declared globally

It solves the problem with var:

let nameUsingLet = 'Michael'
if(true)
    let nameUsingLet = 'Mike'

console.log(nameUsingLet) //Michael

As you can see, we get the expected output as it is block scoped.

let cannot be re-declared but can be updated within a scope block.

let nameUsingLet = 'Michael'

let nameUsingLet = 'Mike'
//SyntaxError: Identifier 'greeting' has already been declared

if(true)
  /* This is a different scope, so redeclaration here is ok.*/
    let nameUsingLet = 'Michel'
    console.log(nameUsingLet) //Michel


console.log(nameUsingLet) //Michael



Hoisting

let declarations are hoisted but it’s different from var.

console.log(variableUsingLet); // ReferenceError: Cannot access 'a' before initialization
console.log(variableUsingVar); // prints undefined as expected
let variableUsingLet = 10;
console.log(variableUsingLet); // 10
var variableUsingVar = 15;
console.log(window.variableUsingLet); // undefined
console.log(window.variableUsingVar); // 15

It looks like let isn’t hoisted, but it is, let’s understand:
Both variableUsingLet and variableUsingVar are actually initialized as undefined in hoisting stage. But variableUsingVar is inside the storage space of GLOBAL, and variableUsingLet is in a separate memory object called script, where it can be accessed only after assigning some value to it first ie. one can access variableUsingLet only if it is assigned. Thus, it throws a ReferenceError.

Temporal Dead Zone: Time elapsed since the let variable was hoisted until it was initialized with a value.

So any line till before “let variableUsingLet = 10” is the Temporal Dead Zone for variableUsingLet.
Since variableUsingLet is not accessible on global, it’s not accessible in window/this also.
ReferenceError is thrown when variables are in the Temporal Dead Zone, SyntaxError doesn’t even let us run a single line of code.

Finally, let’s learn about const.



Const

Just like the name, const variables are constant, they cannot be redeclared or updated and if we try to do so, we will get an error.

With only var, the way to signify a constant variable was to write the variable name in all caps but it still could be updated and redeclared. const solves this problem along with var scoping problem.

const variableUsingConst = 10;
variableUsingConst = 20;
console.log(variableUsingConst)
//TypeError: Assignment to constant variable.



Scope

It is also block-scoped and works similarly to let.

const nameUsingConst = 'Michael'
if(true)
    const nameUsingConst = 'Mike'

console.log(nameUsingConst) //Michael



Hoisting

It is similarly hoisted as let.

console.log(variableUsingConst); // ReferenceError: Cannot access 'variableUsingConst' before initialization
const variableUsingConst = 10;
console.log(variableUsingConst); // 10



Conclusion

Keyword Scope Updateable Redeclareable Hoisted
var Function scope Yes Yes Yes
let Block scope Yes No No
const Block scope No No No
  • Try using const wherever possible.
  • If not use let, Avoid var.
  • Declare and initialize all variables with let to the top to avoid errors and shrink the Temporal Dead Zone window to zero.

Source link

YOU NEED to Learn Python in 2022! (Business Perspective)

Python is one of the easiest programming languages to get started with. For this reason, the community keeps growing every month.

Because of its simplicity (of the Syntax), Python has become the most popular language.

Besides, Python helps Engineers build great products in many industries and professional domains.
The Programmer’s life gets easier when it comes to having a look at Python.



What about the Python Business Market size?

market-size-market-share.jpg

Python is an open-source language, which means that anyone can use it. However, if you look to an industry such as data analytics, in which Python can be used, the market value is over $10 billion.

Shared by futurelearn.com



Here are the top 10 most common uses of Python by industry

pandemic-hero.png

▪ Insurance: Creating business insights with machine learning.

▪ Retail Banking: Flexible data transformation and manipulation.

▪ Aerospace: Meeting software system deadlines.

▪ Finance: Data mining to identify cross-sell opportunities.

▪ Business Services: API access to financial information

▪ Hardware: Automating network administration

▪ Healthcare: Predicting disease prognosis

▪ Consulting Services: Bespoke web development

▪ InfoTech: IT modernization

▪ Software: Adding extensibility to legacy applications

Shared by appdevelopermagazine.com



Here are 5 World-Class Software Companies That Use Python

COTW-TechAcquisitions-Shareable-2.jpg
(Photo by Visual Capitalist)

Google, Meta (Facebook), Instagram, Netflix, Instagram.
There are plenty of companies searching for Python Developers around the globe.



Hence, I created this Blog to help you out!

Design-Blog-Page-Python.jpg

Hence, Learning Python helps you create Opportunities from jobs to Building Products people use.
I just got into Full-stack development using Python Software Development, React + Python as Tech Stack.



Make sure to follow CodeWithKenn for more articles about:

➞ Learning Python in simple terms

➞ Building Side Projects and SaaS using React + Python

➞ Getting useful Resources and tips for your coding Journey

Stay tuned! More articles are coming out! Feel free to comment and share the articles to support me 🤙



🌎 Let’s connect

Want to start blogging? 🔥Join NOW!




Source link

Task Management App Tutorial with Python

In this tutorial, we’ll first build a simple to-do app in Django using Python. Then we’ll explore some ways we can visualize the resulting data in our database client. Want to build an analytics dashboard or twitter scraper instead? Check out these previous tutorials:



Prerequisites

To fully understand this tutorial, you will need the following:



Python setup



Installing Python

First, let’s install Python using this link. Then, we can select our OS and download it. This tutorial was built on Windows. We can run the command Python --version to check if Python is successfully installed on our system. If Python is installed, we get a response as shown below:

Screenshot of a successful Python install.



Creating a virtual environment

Let’s create an isolated virtual environment for this project. Virtual environments help us avoid installing dependencies globally on our system. This helps to make sure that the dependencies of other projects won’t be included within the dependencies of our current project, even though they’re all on the same local machine. To do that run the following command.

Screenshot of a virtual environment.

Next, activate the virtual environment by navigating to the base directory of our new virtual environment (in our example, it has the name “env”). Then, navigate into the Scripts folder and run the executable file “activate.”

Screenshot of a command line.



Django Setup

You can install Django Web Framework with pip and then follow these steps.



Create a project

Now, let’s create the project. We can do this by running the command django-admin startproject followed by the name of the project (in this case, taskmanagement). The full command should look something like this:

django-admin startproject taskmanagement

Here, we can name the project however we like, but be sure to be descriptive.



Create an app

Let’s navigate to the taskmanagement folder and create an application. To do that we use the command python manage.py startapp then the name of the app, which in our case we’ve named task_management_app.

Screenshot of Python code.

The app is created successfully. We can now open the project in our favorite IDE.



Migrations

In Django, we use migrations to move changes we make to our models (adding a field, deleting a model, etc.) into our database schema. First, we need to make migrations to our database. Run the command python manage.py makemigrations. makemigrations are used to create new migrations based on the changes made to the models in a project. The output is as shown below.

Screenshot of Python code

Now let’s run our app to see if we have successfully installed and our project properly set up. To do this, we are to change the directory into our project and run the command python manage.py runserver:

Screenshot of server spinup.

We have started our development server at http://127.0.01:8000/! So we can now open our browser to access our app using this URL. If everything works fine, the screen with the same image below is displayed as the default Django page.

Default project landing page.

Now we want to make some configurations inside the settings.py file. The primary thing we will do is add the app’s name in the installed apps, as seen directly below, and then add the MySQL database to Django.

Adding app to the list of installed apps.



Editing Settings.py to add MySQL to Django

In your settings.py file, edit the code below and replace it with the details required to connect to your SQL server:

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database_name',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'username',
        'PASSWORD': 'password',
    



Todo list app data model

Next, we want to create a model. This model will determine how the task will be stored on the database. The task will have seven properties, a title, a description of the task, a startTime, an endTime, a completed status, and a created on and an updated on column to mark when our task was first created and updated.

Note: our startTime and endTime use the DateTime class. This will hold the date and time in which the task was started and completed respectively. We have set created_on field’s auto_now_addproperty to true. This automatically fills this field with the current date and time in which the task was created.

Screenshot of defining the fields.

Now let’s go ahead and make migrations. Any time changes are made to our models, we need to make migrations. Once that is completed, we will find a new file inside the migrations folder as shown below.

Screenshot of Python code.

We didn’t write this code manually. This is the SQL code that Django has handled for us. Next, we migrate with python manage.py migrate. Migrate is responsible for applying and reapplying migrations.

Running the migrations.

Now we test that the CRUD operation was successful by registering the task on the admin panel as follows:

from django.contrib import admin
from .models import Task

class TaskAdmin(admin.ModelAdmin):
      list_display = ("title", "description", "startTime",  "endTime", "completed", "created_on", "updated_on")

admin.site.register(Task, TaskAdmin)

Screenshot of IDE



Task management API

To build the API we will install and use the Django REST Framework.



Creating a superuser and adding the rest_framework

Let’s create a superuser with the following command: python manage.py createsuperuser

Screenshot of creating a superuser

Next, we’ll need to add the Django rest_framework to the list of installed apps.

Screenshot of IDE



Creating the serializers

JSON stands for JavaScript Object Notation. Serializers convert the model class to JSON so that the frontend can work with the received data.

from django.db.models.fields import Field
from rest_framework import serializers
from .models import Task


class TaskSerializers(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ("id", "title", "description", "startTime", "endTime", "completed", "created_on", "updated_on")



Creating the view

The view is simply a Python function that takes an HTTP request and returns a response. This response may be the HTML contents, for example. The view itself houses the business logic that is necessary to return a response to a client that makes an HTTP call to it.

from django.db.models.query import QuerySet
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import TaskSerializers
from .models import Task

# Create your views here.

class TaskView(viewsets.ModelViewSet):
    serializer_class = TaskSerializers
    queryset = Task.objects.all()

Screenshot of IDE



The URL

The URL is used to map path expressions to Python functions (your views). It first receives HTTP requests and routes them to the right matching function in views.py to handle the request. Now let’s go to the URL that is in the project folder and add the following code:

from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from task_management_app import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'tasks', views.TaskView, 'task')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]

Screenshot of IDE.



Accessing our endpoints

To access our endpoint run your app and visit http://127.0.0.1:8000/api/tasks/ and add a task.

Screenshot of application.

Boom! We have it on our task manager. We can get a particular task by appending the Id of the task to the URL. We can also update or delete a particular task.

This section has taught us how to build a task management app that performs CRUD operations. Now, we will use a SQL client to visualize the data on our database.



Visualize and query task data

Next, we select the SQL type we are most familiar with. In the course of this article, we would be connecting to a MySQL relational database.

Connecting to the DB.



Visualizing tables

I made a sample data .csv for this tutorial. First, I created a Google sheet, exported it to a .csv, and then imported it. This data table contains columns: id, title, description, completed, created on, startTime, endTime, and updated on. This is our exported data set in Table view:

Screenshot of Arctype.



Creating a dashboard to group together activities

Now, we are going to display our list of activities. First, we’ll write an SQL query that will display our data set. Click on the Queries tab by the sidebar and select Create query button.

Screenshot of Arctype

We can start by renaming our query and save it in the editor’s heading:

SELECT COUNT(*) AS tables_priv FROM `excel_for_arctype_data_sheet_1_1`;

The result we get should look like the screenshot below:

Screenshot of Arctype

Next, we can now click on the Dashboard tab to create a new dashboard. Then, we rename our dashboard with our preferred name.

Next, click on “Add tab” and select Chart:

Adding a chart.

Then, click on the select chart data and select activities_count:

Screenshot of Arctype.

Change the title of the dashboard component and select Score Card as the chart type. Then, we can now drag the table_priv column to be displayed.

Screenshot of Arctype.

Next, we create a table component to display the activities that were most productive.

Create a new query called activities_complete. We can then carry out the following commands in it:

SELECT 
    SUM(completed) AS list_of_completed_activities 
FROM 
    `excel_for_arctype_data_sheet_1_1` 
WHERE 
    title = Atitle;

Screenshot of a query in Arctype.

Then, click on the add button from the activity dashboard section we already created and select table:

Screenshot of Arctype

Lastly, we click on the select chart data button and select the Title query we created earlier.

Screenshot of Arctype



Creating a pie chart

Here, we are going to create chart components with Arctype to display our datasets in pie charts.

We start the process by using our previous query command. Then, simply select the chart type and change it to Pie Chart and drag the tables_priv to the column category.



Mixing different types of charts in one dashboard

Here, we are going to create chart components with Arctype to display our datasets in bar charts. We repeat the same process as we did with pie charts.

We change the chart type to Bar Chart and drag tables_priv to the column category. Then, we configure the chart to match whatever settings we want.



Conclusion

This article was divided into two sections. First, we learned how to use a Python framework (Django) to create a task management system. Secondly, we explored the data model of our task management app using a SQL client. While we did that, Arctype to visualize our tables and columns using queries and dashboards. We also learned how to showcase our dataset into pie charts, bar charts, area charts, and line charts.


Source link

ES6: How to Clone an Object in javascript ?

Hey Folks👋 hope you doing well.
So you must be thinking, “Clone an Object”??? whats the big deal?
Well, i also think this way until i encounter an issue which took me 2 days just to debug that i have done something terrible with cloning an object.

So lets see how can we clone objects in javascript

// we have a user object
const user = 
  name:"Deepak Negi",
  email:"st.deepak15@gmail.com"
 

Now, if we want to copy this user object, so? simple!

const copiedUser = user;

Easy right?… well thats the worst way of copying a user,it is clear that you have some misconceptions of what the statement const copiedUser = user; does.

In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so user and copiedUser are both references to the same object.

// [Object1]<--------- user

const copiedUser = user;

// [Object1]<--------- user
//         ^ 
//         |
//         ----------- copiedUser

As you can see after the assignment, both references are pointing to the same object.

const user = 
  name:"Deepak Negi",
  email:"st.deepak15@gmail.com"
  
const copiedUser = user;
copiedUser.name = "XYZ"
console.log(copiedUser) // name:"XYZ",email:"st.deepak15@gmail.com"
console.log(user) // name:"XYZ",email:"st.deepak15@gmail.com"

modifing any of them will change both of them 🙁

So then how we can create copy if we need to modify one and not the other?

1. Spread Operator

const spreadUser = ...user
spreadUser.name = "XYZ"
console.log(spreadUser) // name:"XYZ",email:"st.deepak15@gmail.com"
console.log(user) // name:"Deepak Negi",email:"st.deepak15@gmail.com"

2. Object.assign()

const assignUser = Object.assign(, user);
assignUser.name = "XYZ"
console.log(assignUser) // name:"XYZ",email:"st.deepak15@gmail.com"
console.log(user) // name:"Deepak Negi",email:"st.deepak15@gmail.com"

Yaassss we finally got it!

If you think thats it.. so no… there much more to know, now we have added some more data in the user object and now lets see what happen.

const user = 
  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"New Delhi",
    state:"Delhi",
    zipcode: 000000,
    country:"India"
  

const spreadUser = ...user
spreadUser.address.city = "Pune"
spreadUser.address.state = "Mumbai"

console.log(spreadUser)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"Pune",
    state:"Mumbai",
    zipcode: 000000,
    country:"India"
  


console.log(user)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"Pune",
    state:"Mumbai",
    zipcode: 000000,
    country:"India"
  

You see the problem, our actual user object is also changed now and this happens with Object.assign() method as well.

But why?
Because of the shallow copying i.e. object spread operator, as well as Object.assign, does not clone the values of nested objects, but copies the reference to the nested object. That’s called shallow copying.

Then what should we do? Deep copy?
Yes, Deep copy/Deep clone will copies object, even nested properties, to do so serialize the object to JSON and parse it back to a JS object.

const user = 
  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"New Delhi",
    state:"Delhi",
    zipcode: 000000,
    country:"India"
  

const deepCopiedUser = JSON.parse(JSON.stringify(user))

deepCopiedUser.address.city = "Pune"
deepCopiedUser.address.state = "Mumbai"

console.log(deepCopiedUser)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"Pune",
    state:"Mumbai",
    zipcode: 000000,
    country:"India"
  


console.log(user)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"New Delhi",
    state:"Delhi",
    zipcode: 000000,
    country:"India"
  


So now our original user object doesn’t change when we modify the deepCopiedUser.

Beware using the JSON.parse(JSON.stringify(user)) if you’re dealing with date, functions, RegExps, Maps, Sets or other complex types within your object. The JSON method can’t handle these types.

So for such cases the lodash clonedeep method is probably the best way to go.

import cloneDeep from 'lodash'
or
const cloneDeep = require('lodash')

const user = 
  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"New Delhi",
    state:"Delhi",
    zipcode: 000000,
    country:"India"
  

const deepCloneUser = cloneDeep(user)
deepCloneUser.address.city = "Pune"
deepCloneUser.address.state = "Mumbai"

console.log(deepCloneUser)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"Pune",
    state:"Mumbai",
    zipcode: 000000,
    country:"India"
  


console.log(user)
// console output 

  name:"Deepak Negi",
  email:"st.deepak15@gmail.com",
  address:
    line1:"ABC, Tower X",
    city:"New Delhi",
    state:"Delhi",
    zipcode: 000000,
    country:"India"
  

Finally!!

Let me know in the comment what do you think the best way for deep cloning the object.


Source link

HTML 5 – The Brainstorm!

Hello tribe! today we are going to talk about the html tags that go inside the head of the document! Bring out the umbrella because it’s raining brains! halleluyah! 🎼

As we had mentioned so far, in the structure of an HTML document there are two main HTML tags: “head” and “body” . The head tag contains the metadata tags (information about the document) as well as making connections or relationships with other documents and the body tag allows us to display the content.



“Connection” tags:

  • Title : title of the web page
  • meta: where you set data such as the language developed on the page.
  • Script: to load js
  • Style: to load css on the current page
  • Link:In my opinion the most important because it allows to load css, improves SEO, establishes relationships with other pages, or alternative versions of our website etc… It is the Swiss knife of tags!



Examples

<head>
        <title>My cute page</title>
        <meta charset="utf-8">
        <link rel="alternate" href="document-en.html" hreflang="en" /> //create a alternative page
</head>

👁 Script is best placed in the body and Style with a link.



Meta tag:

Perhaps the tag with the greatest number of possibilities in the header of an HTML document is the tag. In it, and through attributes, we can indicate a large amount of metadata to the document.

Meta has the following attributes:

  • description
  • keywords
  • author
  • language
  • generator
  • theme-color
  • viewport

If you want me to go deeper into tags, let me know in the comments! Well tribe that’s all for now, see you in the next post and remember to always be the best version of you!


Source link