dxalxmur.com

A Comprehensive Guide to Handy JavaScript One-Liners

Written on

Chapter 1: Introduction

Recently, I came across some intriguing articles about one-liners in JavaScript. Inspired by them, I decided to compile a collection to share with you. I trust this will prove beneficial in your coding endeavors. Although some of these methods may lack elegance, the primary goal of this article is to enhance your skills with various APIs.

Chapter 2: Date Operations

  1. Validating a Date

    This one-liner checks if a provided date is valid.

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 27, 2022 13:14:00"); // true
  1. Calculating Date Intervals

    Use this to find the difference between two dates.

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDif(new Date("2022-08-27"), new Date("2022-12-25")); // 120

120 days until Christmas.

  1. Finding the Day of the Year

    This method reveals which day of the year a specific date falls on.

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 239

239 days have passed in 2022.

  1. Time Formatting

    Convert a date into an hh:mm:ss format.

const timeFromDate = date => date.toTimeString().slice(0, 8);

timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00

For the current time:

timeFromDate(new Date()); // now time 09:00:00

Chapter 3: String Manipulation

  1. Capitalizing the First Letter

    This method capitalizes the first character of a string.

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

capitalize("hello world"); // Hello world
  1. Reversing a String

    Use this to reverse a given string.

const reverse = str => str.split('').reverse().join('');

reverse('hello world'); // 'dlrow olleh'
  1. Generating a Random String

    This method creates a random string.

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

randomString();
  1. String Truncation

    Truncate a string to a specified length.

const truncateString = (string, length) => string.length < length ? string : ${string.slice(0, length - 3)}...;

truncateString('Hi, I should be truncated because I am too loooong!', 36); // 'Hi, I should be truncated because...'
  1. Removing HTML from a String

    This method strips HTML tags from a string.

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

Chapter 4: Array Processing

  1. Removing Duplicates

    This method eliminates duplicate items from an array.

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

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
  1. Checking Array Emptiness

    Determine if an array is empty.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]); // true
  1. Merging Arrays

    Combine two arrays using the following methods.

const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];

Chapter 5: Numerical Operations

  1. Odd or Even Check

    This method determines if a number is odd or even.

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

isEven(996);
  1. Calculating the Average

    Get the average of a set of numbers.

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

average(1, 2, 3, 4, 5); // 3
  1. Generating a Random Integer

    This method retrieves a random integer between two numbers.

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

random(1, 50);
  1. Rounding to Specific Digits

    Round a number to a certain number of decimal places.

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d);

round(1.005, 2); // 1.01

round(1.555, 2); // 1.56

Chapter 6: Color Manipulation

  1. RGB to Hex Conversion

    Convert RGB values to hexadecimal format.

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255); // '#ffffff'
  1. Random Hexadecimal Color

    Generate a random hexadecimal color value.

const randomHex = () => #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")};

randomHex();

Chapter 7: Browser Operations

  1. Copying Text to Clipboard

    Copy text to the clipboard using this method.

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");
  1. Clearing Cookies

    Remove all cookies stored on the web page.

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, =;expires=${new Date(0).toUTCString()};path=/));

  1. Getting Selected Text

    Retrieve the text selected by the user.

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

getSelectedText();
  1. Checking Dark Mode

    Determine if the current environment is using dark mode.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

console.log(isDarkMode);
  1. Navigating to the Top of the Page

    Return to the top of the page.

const goToTop = () => window.scrollTo(0, 0);

goToTop();
  1. Tab Activity Check

    Check if the current tab is active.

const isTabInView = () => !document.hidden;

  1. Apple Device Detection

    Determine if the current device is an Apple device.

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

isAppleDevice();
  1. Scroll Detection

    Check if the page is scrolled to the bottom.

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

  1. URL Redirection

    Redirect to a specified URL.

const redirect = url => location.href = url;

  1. Opening Print Dialog

    Open the browser's print dialog.

const showPrintDialog = () => window.print();

Chapter 8: Additional Utilities

  1. Random Boolean Value

    Generate a random Boolean value.

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

randomBoolean();
  1. Variable Swapping

    Swap the values of two variables without a temporary variable.

[foo, bar] = [bar, foo];

  1. Getting Variable Type

    Retrieve the type of a variable.

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

trueTypeOf(''); // string

trueTypeOf(0); // number

trueTypeOf(); // undefined

trueTypeOf(null); // null

trueTypeOf({}); // object

trueTypeOf([]); // array

trueTypeOf(0); // number

trueTypeOf(() => {}); // function

  1. Temperature Conversion

    Convert between Celsius and Fahrenheit.

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

celsiusToFahrenheit(15); // 59

celsiusToFahrenheit(0); // 32

celsiusToFahrenheit(-20); // -4

fahrenheitToCelsius(59); // 15

fahrenheitToCelsius(32); // 0

  1. Checking Object Emptiness

    Verify if a JavaScript object is empty.

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

Feel free to follow me on Twitter, LinkedIn, and GitHub! Writing is my passion, and I take pleasure in helping and inspiring others. If you have any inquiries, don't hesitate to reach out!

For more content, visit PlainEnglish.io and subscribe to our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# 9 Essential Strategies for Leading a High-Performing Team

Discover nine effective strategies to lead your team toward success while fostering a culture of trust and communication.

# The Enigmatic Yellow Glass Scarab from King Tutankhamun's Tomb

Explore the origins of the yellow glass scarab found in King Tutankhamun's tomb, blending science and history to uncover its secrets.

Exploring Exoplanets: Clues to Life Beyond Earth

Investigating exoplanets may reveal vital clues about potential life beyond Earth through their unique geological and atmospheric characteristics.

# Enhancing Role Clarity: A Key to Engineering Team Success

Discover how clear roles in engineering teams can improve performance and prevent common organizational issues.

Top 8 Online Side Hustle Ideas for Earning Extra Income Monthly

Explore the best online side hustle ideas to boost your income from the comfort of your home.

Understanding Uber's Architectural Evolution from 2009 to 2016

Explore Uber's architectural decisions and growth challenges from 2009 to 2016.

Understanding the True Nature of Myths and Their Significance

Exploring the real meaning of myths and their role in history and religion.

Revolutionary Use of Honeybees in Explosive Detection Technology

Researchers are training honeybees to detect explosives, offering a promising alternative to traditional methods.