Javascript: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 135: Line 135:
</syntaxhighlight>
</syntaxhighlight>


===Remove Element to array in Object===
===Remove Element from array in Object===
Here is an example of removing an element from a given index
Here is an example of removing an element from a given index
<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
Line 159: Line 159:
       ...user.cookies.slice(tokenIndex + 1),
       ...user.cookies.slice(tokenIndex + 1),
     ];
     ];
</syntaxhighlight>
===Replace an Element in an Object array===
Replace a use in an array of users.
<syntaxhighlight lang="js">
    this.userCollection = this.userCollection.map((user) => {
      let temp = user;
      if (temp.id === user.id) {
        temp = newUser;
      }
      return temp;
    });


</syntaxhighlight>
</syntaxhighlight>

Revision as of 23:43, 2 July 2021

Javascript tips

One Liners

Get count from Object

cart.map(item => item.quantity).reduce(previous, next) => previous + next,0) : 0}

Variables

let a = 50; // Can be changed but only valid in scope
var a = 50; // Can be changed but global
const a = 50 // Cannot be changed

Objects

You can create an object using this

const sessionId = 1;
const burke1 = sessionId
const burke2 = sessionId +1
const burke3 = sessionId +2
const burke4 = sessionId +3
const burke5 = sessionId +4

const mee = {
  burke1,
  burke2,
  burke3,
  burke4,
  burke5,
}

Will create a object with keys the same name as the values e.g.

mee.burke1 // = 1
mee.burke2 // = 2

Class Field declarations

You can declare classes like

testData = {
  { name = "Fred", age = 20 }
  { name = "Freda", age = 30 }
}

This will simplify the class state e.g. was

class App Extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            profile: testData,
        } 
    }
}

To

class App Extends React.Component {

    state = {
       profile: testData,
    }
}

Property Syntax

You can reference a property of an object via a variable. In the example below we have assigned c to myPropertyName.

const myPropertyName = 'c'

const myObject = {
  a: 5,
  b: 10,
  [myPropertyName]: 15
} 

console.log(myObject.c) // prints 15

Comparisons

The following would be true with loose comparisons

    if("20" == 20) {
       console.log("true");
    }
    else {
       console.log("false");
    }

But false with strict comparisons

    if("20" === 20) {
       console.log("true");
    }
    else {
       console.log("false");
    }

This is because the type is compared in strict comparisons

Array

Introduction

This is about immutable array because it seems this is the way with javascript.

Add Element to array in Object

Here is an example of adding an element

    // Given
    user = {
       name: "fred"
       surnname: "blogss", {
          cookies: [
             "token1",
             "token2",
             "token3"
          ]
       }
    }

    // Add the cookie to the user
    const newCookies = [...user.cookies, refreshToken];

    // Replace the cookies with the newCookies
    const newUser = { ...user, cookies: newCookies };

Remove Element from array in Object

Here is an example of removing an element from a given index

    // Given
    user = {
       name: "fred"
       surnname: "blogss", {
          cookies: [
             "token1",
             "token2",
             "token3"
          ]
       }
    }

    // We can remove the one we want with
    const tokenIndex = user.cookies.findIndex(
        (token) => token === refreshToken
    );

    const newCookies = [
      ...user.cookies.slice(0, tokenIndex),
      ...user.cookies.slice(tokenIndex + 1),
    ];

Replace an Element in an Object array

Replace a use in an array of users.

    this.userCollection = this.userCollection.map((user) => {
      let temp = user;
      if (temp.id === user.id) {
        temp = newUser;
      }
      return temp;
    });

Add

    const newArray = myArray.concat(newElement)

Filter

    const newArray = myArray.filter(
        n=> !myOtherArray.includes(n)
    }

Spread

Spreading array

const testData = {
  { name = "Fred", age = 20 }
  { name = "Freda", age = 30 }
}

Spread spreads them e.g.

    <Card {...testData[0]} />
    <Card {...testData[1]} />

Is the same as

    <Card { name="Fred"  age=20} />
    <Card { name="Freda" age=30} />

Appending to an array

    testData: [...prevState.testData, newTestData]

Map

Given we can spread elements we can also spread array e.g

    <div>
        {testData.map( element=> <Card {...element} />) }
    </div>

functions

Assign function to variable

Simple Functions

const X = () => {
   console.log("Fred");
}

Arrow Functions

Not great for me so need to write it down.

Normal controller no function

  router.get('/customers', (req, res) => {
    console.log('this is me');
    // console.log(req.query);
    res.sendStatus(404);
  });

Let put if in a function. We need to make the function signature match the original

function iain(req, res) {
    console.log('this is me');
    console.log(req.query);
    res.sendStatus(404);
}

router.get('/customers', iain)

async now is

async function iain(req, res) {
    console.log('this is me');
    console.log(req.query);
    res.sendStatus(404);
}

router.get('/customers', iain)

Importing

Using export instead of export default means you have to use destruction to import e.g.

import {ActionTypes as types} from '../constants';

For this example constants.js file

import keyMirror from 'keyMirror';

export var ActionType = keyMirror ({
    THIS_IS_A_CONST = null
});

destructure

// const PI = Math.PI;
// const E = Math.E;
// const SQRT2 = Math.SQRT2; 

// Does the same
const {PI, E, SQRT2} = Math;

You can pass a cirucla to and the radius is automatically extracted. Precision can have a default but can also be passed.

const circle = {
    label: 'circleX',
    radius: 2,
};

const circleArea = {{radius}, {precision = 2} = {}) =>
  (PI * radius * radius).toFixed(precision);

console.log(
  circleArea(circle, {precision:5})
);


And arrays

const [first, ...restOfItems] = [10,20,30,40]

// First be 10, restOfitems is and array of 20,30,40

Template Strings

This is like c# interpolation using back ticks.

const html = `<div>${Math.random()}</div>`;

Promises and Async

Old approach to async

const fetchData = async () => {
  const resp = await fetch('https://api.github.com');
  const data = await resp.json();
  console.log(data);
};

fetchData();

New approach

const fetchData = async() => {

  const resp = await fetch('http::/api.github.com');
  const data = await resp.json();

  console.log(data);
}

fetchData();

Generators

The function * denotes a generator function. The function is executed until yield. Subsequent calls remember the value of yield and continue to the next yield

 function * myGen(i) 
 {
    while(true)
    {
       yield i = i * 10;
    }
 }

 fred = myGen(10);

 console.log(fred.next());
 console.log("Fred was ere 1");

 console.log(fred.next());
 console.log("Fred was ere 2");

 console.log(fred.next());
 console.log("Fred was ere 3");

Output would be{ value: 100, done: false }

Fred was ere 1
{ value: 1000, done: false }
Fred was ere 2
{ value: 10000, done: false }
Fred was ere 3

react functions and state

Normal function

function logRandom() {
    console.log(Math.random());
}

function Button() {
 const [count, setCounter] = useState(0);
 return <button onClick={logRandom}>{counter}</button>;
}

inline function

function Button() {
 const [count, setCounter] = useState(0);
 return <button onClick={

  function logRandom() {
      console.log(Math.random());
  }

 }>{counter}</button>;
}

inline arrow function definition

function Button() {

 // React useState hook
 const [count, setCounter] = useState(0);

 return <button 
   onClick={
      () = > console.log(Math.random())
   }
  >{counter}</button>;
}

Passing Props

function Button(props) {
  const handleClick = () => props.onClickFunction(props.increment);
	return (
  	<button onClick={handleClick}>
      +{props.increment}
    </button>
  );
}

function Display(props) {
	return (
  	<div>{props.message}</div>
  );
}

function App() {
	const [counter, setCounter] = useState(0);
  const incrementCounter = (incrementValue) => setCounter(counter+incrementValue);
	return (
    <div>
      <Button onClickFunction={incrementCounter} increment={1} />
      <Button onClickFunction={incrementCounter} increment={5} />
      <Button onClickFunction={incrementCounter} increment={10} />
      <Button onClickFunction={incrementCounter} increment={100} />
      <Display message={counter}/>
    </div>  
  );
}

ReactDOM.render(
  <App />, 
  document.getElementById('mountNode'),
);