Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Last active May 24, 2023 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beyarz/daaa9bbe6d7b5dbe79d1e51214f5afdc to your computer and use it in GitHub Desktop.
Save Beyarz/daaa9bbe6d7b5dbe79d1e51214f5afdc to your computer and use it in GitHub Desktop.
Javascript tips, tricks & shorthands
// Javascript nullish coalescing operator
// Is set to 0
let x = 0 ?? "hello"
// Is set to goodbye
let y = undefined ?? "goodbye"
// Is set to hello
let z = null ?? "hello"
// Is set to false
let a = false ?? "goodbye"
// Src: https://hackernoon.com/understanding-nullish-coalescing-or-in-javascript
// Run anonymous function on load
(() => console.log(1))()
// Sum of array
const data = [
{ index: 1 },
{ index: 2 },
{ index: 3 },
]
// Don't
let sum = 0
data.forEach(el => {
sum += el.index
})
// Do
data
.map(el => el.index)
.reduce((a, b) => a + b)
async function setupCamera() {
video = document.getElementById("video")
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
facingMode: "user",
// Only setting the video to a specified size in order to accommodate a
// point cloud, so on mobile devices accept the default size.
width: mobile ? undefined : VIDEO_SIZE,
height: mobile ? undefined : VIDEO_SIZE
}
})
video.srcObject = stream
return new Promise(resolve => {
video.onloadedmetadata = () => {
resolve(video)
}
})
}
// clone using slice()
> let a = [1]
> let b = a
> let c = a.slice()
> a.push(2)
> b.push(3)
> c.push(4)
> a
[ 1, 2, 3 ]
> b
[ 1, 2, 3 ]
> c
[ 1, 4 ]
function closure() {
let countState = 0
function change(value) {
return countState += value
}
return {
increment: () => change(1),
decrement: () => change(-1),
value: () => countState,
}
}
// <- a.value()
// -> 0
// <- a.increment()
// -> 1
// <- a.decrement()
// -> 0
// Get element by custom attribute and value
document.querySelectorAll('[custom-attribute="value"]')
const date = new Date()
const localDate = new Intl.DateTimeFormat('sv-SE').format(date)
// YYYY-MM-DD
console.log(localDate)
// 2022-05-21 23:39:02
new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString()
// Check if date is within timespan
var numDaysBetween = function(d1, d2) {
var diff = Math.abs(d1.getTime() - d2.getTime());
return diff / (1000 * 60 * 60 * 24);
};
var d1 = new Date(2011, 0, 1); // Jan 1, 2011
var d2 = new Date(2011, 0, 2); // Jan 2, 2011
numDaysBetween(d1, d2); // => 1
var d3 = new Date(2010, 0, 1); // Jan 1, 2010
numDaysBetween(d1, d3); // => 365
// src: https://stackoverflow.com/questions/6154689/how-to-check-if-date-is-within-30-days
// Get number of days between two dates, https://gist.github.com/qianlongo/3ebc9ef362e2d6092b0ffa669e778fcd
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1"))
// Do N times, 4 different ways
Array.from(Array(3)).forEach((_, i) => console.log(i))
Array.from({length: 3}, (_, i) => console.log(i))
[...Array(3)].map((_, i) => console.log(i))
for( let i = 3; i--; )
console.log(i)

Express.js

Default generator config

npx express-generator --view=ejs --css=sass --git

# Coffeescript invalid syntax
# Valid syntax
[1, 2, 3].map((el) -> el % 2 == 0)
# Invalid syntax
[1, 2, 3].map(el -> el % 2 == 0)
# This is because it transpiles down to the following js
# Valid syntax
# [1, 2, 3].map(function(el) {
# return el % 2 === 0;
# });
# Invalid syntax
# [1, 2, 3].map(el(function() {
# return el % 2 === 0;
# }));
function isMobile() {
const isAndroid = /Android/i.test(navigator.userAgent);
const isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
return isAndroid || isiOS;
}
// .isString() in js javascript
Object.prototype.isString = function () {
return this === "string"
}
const a = "test"
a.isString() // true
const b = 123
a.isString() // false
// "HH:MM:SS"
new Date().toLocaleString(navigator.language || 'sv-SE', { hour: 'numeric', minute: 'numeric', 'second': 'numeric'})
// Javascript OR operator
// Is set to 5
let y = 0 || 5
// Is set to "default text"
let x = "" || "default text"
// Src: https://hackernoon.com/understanding-nullish-coalescing-or-in-javascript
// Get user position
navigator.geolocation.getCurrentPosition((value) => { console.log(value)})
// Generate a random string
const list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
let string = "";
for(var x = 0; x <= 10; x++) {
string += list[Math.floor(Math.random() * Math.floor(25))];
}
console.log("String: " + string);
// Shorter way, https://gist.github.com/qianlongo/0062045aaa6cd3f069d5d63a8df12f52
const randomString = () => Math.random().toString(36).slice(2)
randomString()
import { computed } from 'vue/composition-api'
// Bad
const test = computed(() => {
if(root.cart) return root.cart.promotions
return []
})
// Good
const test = computed(() => root.cart?.promotions || [])
const date = new Date()
const time = date.getHours() + ':' + date.getMinutes()
console.log(time) // HH:MM
let date = new Date()
typeof date
// => 'object'
Object.protoype.toString.call(date)
// => '[object Date]'
{}.toString.call(date)
// => '[object Date]'
date.constructor.name
// 'Date'
date instanceOf Date
// True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment