Giter VIP home page Giter VIP logo

javascript-one-liners's Introduction

JavaScript One Liners


ARRAY

Check if a variable is an Array

const isArray = Array.isArray(arr);
const isArray = arr instanceof Array;

Sum of an Array of Number

const sum = (arr) => arr.reduce((a, b) => a + b);

Average of an Array of Number

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;

Sort an Array

const sort = (arr) => arr.slice().sort((a, b) => a - b);

Clone an Array

const clone = (arr) => arr.slice();
const clone = (arr) => [...arr];

Find Unique Values in an Array

const findUniqueValues = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));

Get the Last Element from an Array

const lastElement = (arr) => arr[arr.length-1];
const lastElement = (arr) => arr.slice(-1)[0];
const lastElement = (arr) => arr.slice().pop();

Shuffle an Array

const shuffle = (arr) => arr.slice().sort(() => Math.random() - 0.5);

Remove Duplicates from an Array

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

Merge two Arrays

const merge = (arr1, arr2) => [].concat(arr1, arr2);
const merge = (arr1, arr2) => [...arr1, ...arr2];

Merge and Remove the Duplications

const merge = (arr1, arr2) => [...new Set(arr1.concat(arr2))];
const merge = (arr1, arr2) => [...new Set([...arr1, ...arr2])];

Remove Falsy value from Array

const removeFalsyValues = (arr) => arr.filter(x => x);
const removeFalsyValues = (arr) => arr.filter(Boolean);


STRING

Capitalize a String

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

String Reverse

const reverseString = (str) => str.split("").reverse().join("");
const reverseString = (str) => [...str].reverse().join();

Convert a String to a Number

const toNumber = (str) => Number(str);
const toNumber = (str) => +str;

Convert a String to a Character Array

const toCharArray = (str) => str.split('');
const toCharArray = (str) => [...str];
const toCharArray = (str) => Array.from(str);
const toCharArray = (str) => Object.assign([], str);

Convert Snake case to Camel case

const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (word) => word.toUpperCase().substr(1));


DATE

Days between two dates

const daysBetweenDates = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));

Weekday of a Date

const getWeekday = (date) => ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
const getWeekday = (date) => date.toLocaleString('en-US', {weekday: 'long'});


RANDOM

Random Number Generator

const randomNumber = (rangeStart, rangeEnd) => new Date().getTime() % rangeEnd + rangeStart;
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

Random Hexadecimal Color Generator

const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

Random Boolean Generator

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


VALIDATION

Check if an Array Is Empty

const isEmpty = (arr) => !Array.isArray(arr) || !arr.length;

Check if Array includes a Value

const includes = (arr, value) => arr.indexOf(value) != -1;
const includes = (arr, value) => arr.includes(value);

Check if the date is Weekend

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


REGULAR EXPRESSION

Phone Validation

const checkPhoneNumber = (phone) => (/^(\+91|0)?\s?\d{10}$/).test(phone);

CamelCase Validation

const isCamelCase = (str) => (/^[a-z][a-zA-Z0-9]$/).test(str);


MISCELLANEOUS

Get selected text

const getSelectedText = () => window.getSelection().toString();

Toggle a Boolean

const toggle = (flag) => !flag;

Swap to Variables

const swap = (a,b) => [a,b] = [b,a];


Reference

javascript-one-liners's People

Contributors

khalidsaifullahfuad avatar baymax-hiro avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.