Skip to content

roeib/JavaScript-snippets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 

Repository files navigation

JavaScript-snippets

find us on Facebook

How to generate a random number in a given range

// Returns a random number(float) between min (inclusive) and max (exclusive) 

const getRandomNumber = (min, max) => Math.random() * (max - min) + min;

getRandomNumber(2, 10)

 // Returns a random number(int) between min (inclusive) and max (inclusive)

const getRandomNumberInclusive =(min, max)=> {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

getRandomNumberInclusive(2, 10);

How to find the difference between two arrays.

const firstArr = [5, 2, 1];
const secondArr = [1, 2, 3, 4, 5];

const diff = [
    ...secondArr.filter(x => !firstArr.includes(x)),					
    ...firstArr.filter(x => !secondArr.includes(x))
];
console.log('diff',diff) //[3,4]


function arrayDiff(a, b) {
    return [
        ...a.filter(x => b.indexOf(x) === -1),
        ...b.filter(x => a.indexOf(x) === -1)
    ]
}
console.log('arrayDiff',arrayDiff(firstArr, secondArr)) //[3,4]




const difference = (a, b) => {
    const setA = new Set(a);
    const setB = new Set(b);

    return [
        ...a.filter(x => !setB.has(x)),
        ...b.filter(x => !setA.has(x))

    ]
};

difference(firstArr, secondArr); //[3,4]
console.log('difference',difference(firstArr, secondArr))

How to convert truthy/falsy to boolean(true/false)

const myVar = null; 
const mySecondVar = 1; 

console.log( Boolean(myVar) ) // false
console.log( !!myVar ) // false


console.log( Boolean(mySecondVar) ) // true
console.log( !!mySecondVar ) // true

How to repeat a string

let aliens = '';

for(let i = 0 ; i < 6 ; i++){
 aliens += 'πŸ‘½'
}
//πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½

Array(6).join('πŸ‘½')
//πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½


'πŸ‘½'.repeat(6)
//πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½πŸ‘½