📖
Maissen's Grimoire
  • Maissen's Grimoire
  • Html and css grimoire
    • HTML5 Periodical Table
    • HTML Cheat Sheet
    • CSS Cheatsheets
  • Javascript Grimoire
    • JavaScript Cheat Sheet
      • Javascript Array in depth
      • Tagged Template Literals
      • Guard Clauses - The Best Way To Write Complex Conditional Logic
      • JavaScript Optional Chaining
      • JavaScript Null Coalesce
      • What Are Magic Numbers And Why Are They Bad
      • ES6/ECMAScript2015 Cheatsheet
      • First-class and Higher Order Functions: Effective Functional JavaScript
    • Useful JavaScript Tips, Tricks and Best Practices
    • Bits of code
    • Useful JavaScript libraries
      • Components
      • Animation
      • Maps
      • Helpers
      • Presentations
      • Charts
      • Games
      • Audio
      • Images
      • Video
    • Js the right way
  • Angular Grimoire
    • Angular doc
    • Getting Started
    • Angular clean architecture
    • Angular Cheat Sheet
    • TypeScript Cheat Sheet
    • My Favorite Tips and Tricks in Angular
    • NgRx: tips & tricks
    • Bits of code
      • Execute Multiple HTTP Requests in Angular
      • Authentification
        • Angular 8 JWT Authentication with HttpInterceptor and Router
      • Integrations
        • Spring Boot
          • Rest Example
            • Angular,Spring Boot,Spring Data and Rest Example(CRUD)
          • Authentification
            • Angular, Spring Boot: JWT Authentication with Spring Security example
            • Angular Spring Boot Security Oauth2
              • Spring Boot OAUTH2 Role-Based Authorization
              • Spring Boot Security Google Oauth
              • Spring Security OAuth2 User Registration
    • Most used dependency
  • Node Grimoire
    • Express.js 4 Cheatsheet
    • Useful Dependencies
    • How To Use And Write Express Middleware
    • Node.js with SQL databases
      • Node.js Token Based Authentication & Authorization example
      • Node.js Rest APIs example with Express, Sequelize & MySQL
      • Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize
      • Sequelize
        • Sequelize Many-to-Many Association example – Node.js & MySQL
        • Sequelize One-to-Many Association example with Node.js & MySQL
    • Node.js with NOSQL databases
      • Node.js + MongoDB: User Authentication & Authorization with JWT
      • Node.js, Express & MongoDb: Build a CRUD Rest Api example
      • MongoDB One-to-One relationship tutorial with Mongoose example
      • MongoDB One-to-Many Relationship tutorial with Mongoose examples
      • MongoDB Many-to-Many Relationship with Mongoose examples
  • Upload files
    • How to upload multiple files in Node.js
    • Upload & resize multiple images in Node.js using Express, Multer, Sharp
    • Upload/store images in MySQL using Node.js, Express & Multer
    • How to upload/store images in MongoDB using Node.js, Express & Multer
  • React Grimoire
    • React Doc
    • React Grimoire
    • React Cheat Sheet
  • spring boot Grimoire
    • Getting started
    • Spring Boot, Spring Data JPA – Rest CRUD API example
    • Spring Boot Token based Authentication with Spring Security & JWT
  • Mongo Grimoire
    • MongoDb-Mongoose Cheat Sheet
  • Development tools
    • Design Patterns
  • maissen_grimoire
Powered by GitBook
On this page
  • Reduce array to objects in that array
  • Coerce string into a number
  • Backticks reference
  • Dynamic Object
  • Array intersection
  • Array Difference
  • Symmetrical Difference
  • Union
  • find duplicates
  • Javascript ES6/ES5 find in array and change
  • Check if Object has a property
  • ParseJwt without lib

Was this helpful?

  1. Javascript Grimoire

Bits of code

Reduce array to objects in that array

  let array = [
  { v1: "v1", v2: "v2" },
  { v1: "v1", v2: "v2" },
  { v1: "v1", v2: "v2" },
];
let result = array.reduce((currentArry, elementOfTheArry, Index) => {
  currentArry.push(elementOfTheArry.v1);
  return currentArry; // *********  Important ******
}, []);

console.log(result) // result = [ 'v1', 'v1', 'v1' ]

Coerce string into a number

Backticks reference

Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

Features:

  • we can interpolate any kind of expression in the template literals.

  • They can be multi-line.

Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).

Example:

var nameStr = `I'm "Rohit" Jindal`;

To interpolate the variables or expression we can use the ${expression} notation for that.

var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal

Multi-line strings means that you no longer have to use \n for new lines anymore.

Example:

const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);

Output:

Hello Rohit!
How are you?
typeof  +"5" //returns number 
typeof `${5}` // returns string

Dynamic Object

let dynamicProperty ="Dynamic"
const user ={
  name : "maissen",
  email:"ayed.maissen@gmail.com",
  [dynamicProperty]:"this is dynamic"
}
console.log(user);
/* 
Result :
{
  name: 'maissen',
  email: 'ayed.maissen@gmail.com',
  Dynamic: 'this is dynamic'
}
*/

Array intersection

let intersection = arrA.filter(x => arrB.includes(x));

Array Difference

let difference = arrA.filter(x => !arrB.includes(x));

Symmetrical Difference

let difference = arrA
                 .filter(x => !arrB.includes(x))
                 .concat(arrB.filter(x => !arrA.includes(x)));

Union

let union = [...new Set([...arrA, ...arrB)];

find duplicates

  let counts = {};
  array.forEach((x)=> { counts[x] = (counts[x] || 0)+1;})
  return counts

Javascript ES6/ES5 find in array and change

the map loops over each item in the items array and checks if that item has id the same as the id of the item in the const variable. If it finds one, it maps that item which is x to item which is the one in the const variable, otherwise it keeps the same element x in the items array.

Given a changed object and an array:

const item = {...}
let items = [{id:2}, {id:3}, {id:4}];

Update the array with the new object by iterating over the array:

items = items.map(x => (x.id === item.id) ? item : x)

Check if Object has a property

Check if an object have a specific property

const hasOwnProperty = ( x: {}, k: K ): x is O &
                       { [key in K]: unknown } => x.hasOwnProperty(k)
                       
// example to check if object v is an Object 
// supposedly with the type PersonalOrOrg  
// has a property type and type equal 'personal' or
// has a property type and type equal 'organization' 
// with a property of organization of type sting            
const isCurrentWorkspace = (v: unknown): v is PersonalOrOrg<string> 
                            => typeof v === 'object' && !!v 
                            && hasOwnProperty(v, 'type') 
                            && (v.type === 'personal' 
                            || (hasOwnProperty(v, 'organization') 
                            && typeof v.organization === 'string'))

ParseJwt without lib

const parseJwt = (bearer: string) => {
  const [, token] = bearer.trim().split(' ');

  const base64Url = token.split('.')[1]; // token you get
  const base64 = base64Url.replace('-', '+').replace('_', '/');
  const decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));

  return decodedData;
};

export { parseJwt };
PreviousUseful JavaScript Tips, Tricks and Best PracticesNextUseful JavaScript libraries

Last updated 1 year ago

Was this helpful?