These JavaScript one-liners can make your code even more irritating

JavaScript has grown from strength to strength because it is one of the easiest languages ​​to pick up, thus opening the door for new tech geeks in the market. (Question mark face?) Yes, JavaScript can do a lot of great things! There is still much to learn.

Second, what is a one-liner, a one-liner is a code practice in which we perform certain functions with only one line of code.

random boolean value

This function will return a boolean value (true or false) using the Math.random() method.
Math.random creates a random number between 0 and 1, then we check to see if it is greater or less than 0.5.
This means there is a 50/50 chance of getting right or wrong.

const getRandomBoolean = () => Math.random() >= 0.5;

console.log(getRandomBoolean());

// a 50/50 chance of returning true or false

Check if a date falls on a weekend

const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;

console.log(isWeekend(new Date(2021, 4, 14)));

// false (Friday)

console.log(isWeekend(new Date(2021, 4, 15)));

// true (Saturday)

Check if a number is even or odd

const isEven = (num) => num % 2 === 0;

console.log(isEven(5));
// false

console.log(isEven(4));
// true

Get the unique value in the array (array deduplication)

const uniqueArr = (arr) => [...new Set(arr)];

console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]

Check if variable is an array

const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true

console.log(isArray({
    
     name: 'Ovi' }));
// false

console.log(isArray('Hello World'));
// false

Generate a random number between two numbers

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

console.log(random(1, 50));
// could be anything from 1 - 50

Generate random string (unique id?)

const randomString = () => Math.random().toString(36).slice(2);

console.log(randomString());
// could be anything!!!

Toggle Boolean

/ bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
//or
const toggleBool = b => !b;

Calculate the number of days between two dates

To calculate the number of days between two dates,
we first find the absolute value between the two dates, divide it by 86400000 (which equals the number of milliseconds in a day), and finally round the result and return it.

const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199

Different ways to merge multiple arrays

There are two ways to merge arrays. One of them is to use the concat method. The other uses the spread operator (…).
PS: We can also use the "settings" object to copy anything from the final array.

// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];

Get the actual type of javascript language

const trueTypeOf = (obj) => {
    
    
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({
    
    }));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function

truncate the string at the end

const truncateString = (string, length) => {
    
    
  return string.length < length ? string : `${
     
     string.slice(0, length - 3)}...`;
};
console.log(
  truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...


How about truncating a string in the middle ?
The function takes a string as the first parameter, then the size of the string we need as the second parameter, then how many characters do we need to start and end from the 3rd and 4th parameters

const truncateStringMiddle = (string, length, start, end) => {
    
    
  return `${
     
     string.slice(0, start)}...${
     
     string.slice(string.length - end)}`;
};
console.log(
  truncateStringMiddle(
    'A long story goes here but then eventually ends!', // string
    25, // 需要的字符串大小
    13, // 从原始字符串第几位开始截取
    17, // 从原始字符串第几位停止截取
  ),
);
// A long story ... eventually ends!

ternary operator

/ Longhand
const age = 18;
let greetings;
if (age < 18) {
    
    
  greetings = 'You are not old enough';
} else {
    
    
  greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';

Guess you like

Origin blog.csdn.net/weixin_45361998/article/details/121261458