Skip to content

Instantly share code, notes, and snippets.

@simonds
Created July 10, 2021 22:19
Show Gist options
  • Save simonds/5d71102868afe6fa558fe95f5d1758f6 to your computer and use it in GitHub Desktop.
Save simonds/5d71102868afe6fa558fe95f5d1758f6 to your computer and use it in GitHub Desktop.
JavaScript snippets
// Source: https://medium.com/dailyjs/13-javascript-one-liners-thatll-make-you-look-like-a-pro-29a27b6f51cb
const randomBoolean = () => Math.random() >= 0.5;
// randomBoolean() == true || false (a 50/50 change on returning true of false)
const isWeekday = (date) => date.getDay() % 6 !== 0;
// isWeekday(new Date(2021, 0, 11)) == true
const reverse = str => str.split('').reverse().join('');
// reverse('hello world') == 'dlrow olleh'
const isBrowserTabInView = () => document.hidden;
// isBrowserTabInView() == true || false (depending on if tab is in view / focus)
const isEven = num => num % 2 === 0;
// isEven(2) == true
const timeFromDate = date => date.toTimeString().slice(0, 8);
// timeFromDate(new Date(2021, 0, 10, 17, 30, 0)) == "17:30:00"
// timeFromDate(new Date()) == the current time
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// toFixed(25.198726354, 1) == 25.1
// toFixed(25.198726354, 2) == 25.19
// toFixed(25.198726354, 6) == 25.198726
const elementIsInFocus = (el) => (el === document.activeElement);
// elementIsInFocus(anyElement) == true || false (true if in focus, false if not in focus)
const touchSupported = () => {
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
// touchSupported() == true || false (true if touch events are supported, false if not)
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
// isAppleDevice() == true || false (true if user is on an Apple device)
const goToTop = () => window.scrollTo(0, 0);
// Result: will scroll the browser to the top of the page
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
// average(1, 2, 3, 4) == 2.5
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment