Skip to content

Instantly share code, notes, and snippets.

@emreavcilar
Last active April 28, 2022 09:26
Show Gist options
  • Save emreavcilar/1b75d383b63539ebf3270bb9256854b0 to your computer and use it in GitHub Desktop.
Save emreavcilar/1b75d383b63539ebf3270bb9256854b0 to your computer and use it in GitHub Desktop.
/*
all kind of useful functions
*/
/*
The Promise.allSettled method was added to javascript in es2020.
It accepts an array of Promises and only resolves when all of them
are settled - either resolved or rejected. This was not available natively before,
even if some methods like "race" and "all" where available.
*/
const promises = [
Promise.resolve(100),
Promise.resolve(200),
Promise.reject("Oops")
];
Promise.allSettled(promises).then(results => {
console.log(results);
});
// [
// {status: "fulfilled", value:100},
// {status: "fulfilled", value:200},
// {status: "rejected", reason:"Oops"},
// ]
/*
javascript "arguments" is the only Array-like variable that references
variables, and can assign new values to those variables by writing
to the Array. It can not assign new values if no arguments were passed.
*/
function foo(x, y) {
arguments[0] = "hello";
arguments[1] = "world";
console.log(x,y);
}
foo();
//undefined undefined
foo(1,2);
//hello world
/*
This snippet executes a function, returning
either the result or the caught error object.
*/
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
/*
#javascript has a built-in Broadcast Channels API that allows
communication between windows, tabs, iframes and web workers on the same origin.
*/
// create channel
const bc = new BroadcastChannel('my_chan');
//broadcast across windows, tabs, iframes
bc.postMessage('Hello World');
//listen across windows, tabs, iframes
bc.onmessage => (e) => console.log(e);
//destroy the channel
bc.close();
/*
This snippet returns the length of a string in bytes.
*/
const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11
/*
You probably know that you can chain "map" and "filter" and "forEach", etc.
Check out this pattern, and see how you can implement your own custom method chaining
*/
class Dog {
log() {
console.log(this.is)
return this;
}
bark() {
this.is = "woofing";
return this;
}
walk() {
this.is = "walking";
return this;
}
}
const chainableDog = new Dog();
chainableDog
.bark()
.log()
.walk()
.log();
// woofing
// walking
/*
How to style console output?
*/
// To add CSS styling to the console output, we use the CSS format specifier %c.
// Then we start the console message, and the styles we want to apply to the message.
console.log("%cThis is a green text", "color:green");
// --------------------------------------
/*
Log messages can be styled using standard CSS rules
(semicolon separated) passed as a string in the second parameter.
A %c marker in the message indicates where the styling will be applied.
Only the text after the %c directive will be styled.
To add multiple style, you just prepend the message with %c.
console.log('Hi %cthere %cguys', 'color: red', 'color: green');
*/
const styles = [
'color:green',
'background:yellow',
'font-size:30px',
'border:4px solid black',
'text-shadow: 2px px black',
'pading: 10px',
].join(';');
//Concatenate the individual array items
//into a string seperated by a semi-colon
console.log('%cHello there', styles);
// %c applies the style to the following text
/*
JavaScript Tip 💡 Use console.assert to make conditional log
statements. A nice and concise alternative to wrapping console.log in an if-statement.
*/
// Use console.assert to make conditional log statements
// the way you're used to doing it...
if(!user.id){
console.log("User id is missing");
}
// using console.assert
console.assert(user.id , 'User id is missing');
/*
You can assign a console method to a variable, and use bind()
to output a "prefix" string with every message. Turning that
variable into a handy logging utility.
*/
const log = console.log.bind(console, 'App:');
log('Hello world');
// App: Hello world
/*
This snippet uses existsSync() to check whether a
directory exists and then mkdirSync() to create it if it doesn’t.
*/
const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test');
// creates the directory 'test', if it doesn't exist
// https://stackoverflow.com/questions/24163889/html5-input-for-money-currency/54534797#54534797
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = (value || value === 0)
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
/*
This snippet returns the current URL.
*/
const currentURL = () => window.location.href;
currentURL(); // 'https://medium.com/@fatosmorina'
/*
JavaScript Tip 💡
Does your code get bloated from writing try-catch over and over?
How about wrapping your promises in a try-catch once, and returning the result and potential error as a tuple instead?
Now you can resolve promises in a nice and simple way 👌,,https://www.linkedin.com/posts/simonhoiberg_javascript-tip-does-your-code-get-bloated-activity-6897154149478146048-Qk-w
*/
const resolve = async (promise) => {
try {
const result = await promise;
return [result, null];
} catch (error) {
return [null, error];
}
};
const [result, error] = await resolve(
fetch('https://some.api');
)
/*
This snippet delays the execution of a function until the current call stack is cleared.
*/
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
/*
javascript that will delay execution of the next line of code by 2 seconds.
Helpful in debugging async functions that execute too quickly to see what's happening.
*/
await new Promise(res => setTimeout(()=> res(1),2000));
/*
Dynamic imports are a new javascript feature in es2020 that import
JS files dynamically as modules. Allowing you to natively code split
your applications into downloadable chunks. This feature works similar
to webpack and babel dynamic imports.
*/
if(condition){
const module = await import('./module.js');
module.myFunction();
}
/*
you can use String.fromCodePoint() to create emoji characters from a numeric value in javascript.
*/
const smile = String.fromCodePoint(0x1F600);
const str = `Smile ${smile} you're on TV.`;
console.log(str);
// Smile 😀 you're on TV.
console.log(5 ** 2);
// outputs 25
/*
javascript that opens a color picker in #chrome and #edge browsers only. Give it a try in the console!
*/
(new EyeDropper())
.open()
.then(console.log)
/*
Get the file name from a URL in JavaScript
*/
const filename = (url: string): string => url.substring(url.lastIndexOf('/') + 1);
filename('http://domain.com/path/to/document.pdf');
// output 'document.pdf'
/*
js function 4 ways
*/
// functional Declaration
function square(x) {
return x * x;
}
// function expression
const squrea = function (x) {
return x * x;
}
// arrow function expression
const square = (x) => {
return x * x;
}
//concise arrow function expression
const square = x => x * x;
/*
Understanding function hoisting
*/
// Did you know you can call a function before declaring it in JavaScript?
// It happens thanks to hoisting, a mechanism where variables and function declarations are moved to the top of their scope before executing the code.
// However, hoisting DOESN'T work for these syntaxes:
// const myFunction = function() {}
// const myFunction = () => {};
// Hoisting also applies to variables.
// Variables declared with 'let' and 'const' are also hoisted, but unlike for 'var' the variables are not initialized with a default value of undefined.
// Until the line in which they are initialized is executed, any code that accesses these variables will throw an exception.
// --------TRUE
// you can call the function before declaring it
catName('Chloe');
//but only for this declaration syntax
function catName(name) {
console.log("My cat's name is " + name);
}
// --------WRONG
//cannot call these functions before declaring them
catName('Chloe');
dogName('Rex');
// no hoisting
const catName = function (name) {
console.log("My cat's name is " + name);
}
// no hoisting
const dogName = (name) => {
console.log("My dog's name is " + name);
}
/*
This snippet prints the name of a function into the console.
*/
const functionName = fn => (console.debug(fn.name), fn);
functionName(Math.max); // max (logged in debug channel of console)
/*
javascript that generates a random alphanumeric identifier of length 11.
*/
const a = Math.random().toString(36).substring(2);
console.log(a);
// outputs 1275aftx9js
/*
javascript that generates a random hex color.
*/
const color = () => '#'+Math
.floor(Math.random() * 0xffffff)
.toString(16)
.padEnd(6, '0')
console.log(color());
// outputs #2d18b2
/*
When javascript code needs an Array.push() then use a generator function instead with a yield.
*/
//******************************
// WRONG WAY
//******************************
function process(){
const arr = [];
for(let i=0; i<10; i++){
if(someCondition){
arr.push(i);
}
}
return arr;
}
//******************************
// CORRECT WAY
//******************************
function* process(){
for(let i=0; i<10; i++){
if(someCondition){
yield i;
}
}
}
/*
This snippet can be used to get the type of a value.
*/
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
getType(new Set([1, 2, 3])); // 'set'
/*
globalThis was added to javascript in es2020 so that cross-platform code
can run in NodeJs, the web browser and also webworkers and refer
to the same global object. Previously coders used "window", "global"
or "self" but now everyone can use the same "globalThis".
*/
console.log(globalThis === window)
//true
/*
This snippet can be used to redirect from HTTP to HTTPS in a particular domain.
*/
const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};
httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
/*
Self-invoking functions in javascript enable us to execute code once without
cluttering the current context with variables. We can declare private variables
inside the function. These are also known as Immediately Invoked Function Expressions (IIFE).
*/
let result = 0;
let value = (function(a,b){
//private variables
let result = a + b;
return result;
})(10,20);
console.log(value,result);
//30 0
/*
“Imperative programming is like 𝗵𝗼𝘄 you do something, and declarative programming is more like 𝘄𝗵𝗮𝘁 you do.”
That definition makes perfect sense once you actually know the difference between imperative and declarative — but maybe you don’t.
Let's try to understand that difference with 2 examples:
1. A 'double' function which takes in an array of numbers and returns a new array after doubling every item in that array
2. An 'add' function which takes in an array and returns the result of adding up every item in the array
Here you are an imperative and a declarative solution for both of them.
As you can see, with the declarative approach we're describing 𝘄𝗵𝗮𝘁 we want to happen rather than 𝗵𝗼𝘄.
That's why I prefer to be declarative:
- it minimizes mutability
- it reduces state side-effects
- it's more readable
- it's more clear
- it abstracts away complexity
- it's more elegant
- it's shorter
*/
// ------WRONG ----- HOW
function add (numbers) {
let result = 0;
for(let i = 0; i < numbers.length; i++){
result += numbers[i];
}
return result
}
// ---------TRUE ---- WHAT
function add (arr){
return arr.reduce((prev,curr) => prev + curr);
}
//---------------------------------------------------
// -------WRONG ---- HOW
function double (numbers) {
const result = [];
for(let i=0; i< numbers.length; i++){
result.push(numbers[i]*2);
}
return result;
}
// ------TRUE ---- WHAT
function double(arr) {
return arr.map((item)=>item*2)
}
/*
In javascript modules, it was already possible to import namespaces.
However, no symmetric "export" syntax exist until #es2020.
Now we can import and re-export a namespace with one line.
*/
// es2020 namespace exports
export * as utils from './utils.js';
// above is equivalent to
import * as utils from './utils.js';
export {utils};
/*
This snippet can be used to check if a value is of a particular type.
*/
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true
/*
This snippet can be used to check whether an argument is a boolean.
*/
const isBoolean = val => typeof val === 'boolean';
isBoolean(null); // false
isBoolean(false); // true
/*
This snippet can be used to determine whether the current runtime environment is a browser.
This is helpful for avoiding errors when running front-end modules on the server (Node).
*/
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
isBrowser(); // true (browser)
isBrowser(); // false (Node)
/*
This snippet can be used to determine whether the browser tab is focused.
*/
const isBrowserTabFocused = () => !document.hidden;
isBrowserTabFocused(); // true
/*
#javascript shortest code to test for Internet Explorer.
Will be true on IE browsers,
but I'm only sharing for historical reasons only.
*/
var isIE = /*@cc_on!@*/false;
/*
This snippet can be used to check whether a value is null or undefined.
*/
const isNil = val => val === undefined || val === null;
isNil(null); // true
isNil(undefined); // true
/*
This snippet can be used to check whether a value is null.
*/
const isNull = val => val === null;
isNull(null); // true
/*
This snippet checks whether an object looks like a Promise.
*/
const isPromiseLike = obj =>
obj !== null &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function';
isPromiseLike({
then: function() {
return '';
}
}); // true
isPromiseLike(null); // false
isPromiseLike({}); // false
/*
This snippet can be used to check whether an argument is a symbol.
*/
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
/*
This snippet can be used to check whether a value is undefined.
*/
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
/*
This snippet can be used to check whether a string is a valid JSON.
*/
const isValidJSON = str => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(null); // true
/*CSS Functions*/
// Returns the value of an attribute of the selected element
attr();
// Allows you to perform calculations to determine CSS property values
calc();
// Creates a conic gradient
conic-gradient();
// Returns the current value of the named counter
counter();
// Defines a Cubic Bezier curve
cubic-bezier();
// Defines colors using the Hue-Saturation-lightness model (HSL)
hsl();
// Defines colors using the Hue-Saturation-Lightness-Alpha model (HSLA)
hsla();
// Creates a linear gradient
linear-gradient();
// Uses the largest value, from a comma-seperated list of values, as the property value
max();
// Uses the smallest value, from a comma-seperated list of values, as the property value
min();
// Creates a radial gradient
radial-gradient();
// Repeats a conic gradient
repeating-conic-gradient();
// Repeats a linear gradient
repeating-linear-gradient();
// Repeats a radial gradient
repeating-radial-gradient();
// Defines colors using the Red-Green-Blue model (RGB)
rgb();
// Defines colors using the Red-Green-Blue-Alpha model (RGBA)
rgba();
// Inserts the value of a custom property
var();
/* Window Object Method */
// Displays an alert box with a message
alert();
// Removes focus from the current window
blur();
// Clears a timer set with setInterval()
clearInteraval();
// Closes the current window
close();
// Sets focus to the current window
focus();
// Prints the content of the current window
print();
// Requests the browser to call a function pixels to update an animation before next reprint
requestAnimationFrame();
// Scroll the document to the specified coordinates
scrollTo();
// Calls a function or evaluate an expression at specified intervals (in milliseconds)
setInterval();
// Decodes a base-64 encoded string
atob();
// Encodes a string in base-64
btoa();
// Clears a timer set with setTimeout()
clearTimeout();
// Displays a dialog box with a message and with OK and Cancel button
confirm();
// Opens a new browser window
open();
// Displays a dialog box that prompts the visitor for input
prompt();
// Resize the window by the specified
resizeBy()
// Stops the window from loading
stop();
// Calls a function or evaluates an after a specified number o milliseconds
setTimeout();
/*
This snippet can be used to apply the not operator (!) to a predicate function with its arguments.
*/
const negate = func => (...args) => !func(...args);
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
/*
Nullish coalescing operator ?? in javascript was introduced
in es2020 to add the ability of truly checking nullish
values instead of falsey values.
*/
false ?? "truthy"
//false
undefined ?? "truthy"
// "truthy"
null ?? "truthy"
// "truthy"
NaN ?? "truthy"
// NaN
/** compared to || **/
false || "truthy"
// "truthy"
undefined || "truthy"
// "truthy"
null || "truthy"
// "truthy"
NaN || "truthy"
// "truthy"
// Logical nullish assignment (ES2021)
// Before ES12
if(x === null || x === undefined) {
x = y;
}
// or
x ?? (x = y)
// After ES12
x ??= y;
// Example
const song = { duration : 50 };
song.duration ??= 10;
console.log(song.duration) //50
song.speed ??= 25;
console.log(song.speed); //25
/*
javascript example of object-oriented programming vs. functional programming
*/
//****************************
//object oriented animal
//****************************
class Animal {
constructor(name,legs){
this.name = name;
this.legs = legs;
}
info(){
console.log(this.name,this.legs);
}
}
let dog = new Animal('dog',4);
dog.info();
//****************************
//functional animal
//****************************
function animal(name,legs) {
return {name, legs};
}
function animalInfo(self){
console.log(self.name, self.legs);
}
let cat = animal('cat',4);
animalInfo(cat);
/*
prevent the user pasting text by using a paste event listener in javascript
*/
input.addEventListener('paste', function(e){
e.preventDefault();
})
/*
Prevent Pasting into an Input
*/
/*
Even though disable pasting is not always
good for user experience, it can be useful
sometimes.
When?
Maybe you don't want the user copy-paste its
credentials in the relative confirmation fields,
so you can prevent pasting into those input.
*/
// FIRST WAY
confirmEmailInput.addEventListener('paste', e => e.preventDefault());
// SECOND WAY
confirmEmail.onpaste = e => e.preventDefault();
/*
JavaScript Tip 💡 Speed asynchronous tasks up by running them in parallel.
If the tasks don't rely on the result from the previous one, simply wrap them
in Promise.all and run them in parallel. It's much faster
*/
// Run Promises in parallel
// WRONG -----------------------
async function updateUserInfo(){
await updateUser({ id:'abc123', lastLogin: new Date() });
await sendUpdateNotification({ userID: 'abc123' });
await cleanupOldLogs({ userID: 'abc123', cleanAll: true });
}
// TRUE --- MUCH FASTER !!!!!
async function updateUserInfo(){
await Promise.all([
updateUser({ id:'abc123', lastLogin: new Date() });
sendUpdateNotification({ userID: 'abc123' });
cleanupOldLogs({ userID: 'abc123', cleanAll: true });
])
}
/*
This snippet can be used to generate a random hexadecimal color code.
*/
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode(); // "#e34155"
/*
This snippet can be used to read a file by getting an array of lines from a file.
*/
const fs = require('fs');
const readFileLines = filename =>
fs
.readFileSync(filename)
.toString('UTF8')
.split('\n');
let arr = readFileLines('test.txt');
console.log(arr); // ['line1', 'line2', 'line3']
/*
This snippet can be used to do a redirect to a specified URL.
*/
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://google.com');
/*
javascript functions that prompt a user in a web browser to save or load files locally from their own hard drive.
*/
async function save(data) {
const file = await window.showSaveFilePicker();
const writer = await file.createWriteable();
await writer.write(data);
await writer.close();
}
async function load(){
[file] = await window.showOpenFilePicker();
return file.getFile();
}
/*
javascript to read the size of the user's display screen.
You can see how large their monitor is even if the web browser window isn't maximized.
*/
// how big is your monitor ?
const {width, height} = screen;
/*
This snippet can be used to serialize a cookie name-value pair into a Set-Cookie header string.
*/
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
serializeCookie('foo', 'bar'); // 'foo=bar'
// Object.preventExtensions is the first of 3 functions that JavaScript provides to achieve a shallow immutability.
// It prevents objects from being extended, meaning we cannot add properties to the object anymore.
// This is a partial immutability, since we can still edit and delete properties.
// Shallow because it only applies to the first level of nesting.
// PS: It also works with arrays, since they are actually objects.
const avenger = { name: 'Ironman', power: 'Armor' };
Object.preventExtensions(avenger);
avenger.friend = 'Hulk'; // cant add props;
avenger.name = 'War Machine'; // can edit props
delete avenger.power; // can delete props
// avenger : { name: 'War Machine' }
// Object.seal is the second of 3 functions that JavaScript provides to achieve a shallow immutability.
// It "seals" objects, which means we can no longer add or delete properties.
// This is partial immutability, since we can still edit the property values.
// Shallow because it only applies to the first level of nesting.
// PS: It also works with arrays, since they are actually objects.
const avenger = { name: 'Ironman', power: 'Armor' };
Object.seal(avenger);
avenger.friend = 'Hulk'; // cant add props;
avenger.name = 'War Machine'; // can edit props
delete avenger.power; // cant delete props
// avenger : { name: 'War Machine', power: 'Armor' }
// https://www.linkedin.com/posts/simonhoiberg_typescript-tip-looong-import-statements-activity-6897814491560497154-YpNo
// WRONG
import SignUp from '../../../components/signup';
import {userState} from '../../../../store/user';
// TRUE
// Add this to tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src"
}
}
import SignUp from 'components/signup';
import {userState} from '/store/user';
/*
This snippet can be used to delay the execution
of an asynchronous function by putting it into sleep.
*/
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function sleepyWork() {
console.log("I'm going to sleep for 1 second.");
await sleep(1000);
console.log('I woke up after 1 second.');
}
/*
powerful spread operator tricks you should know
*/
// COPY
const arr1 = [1,2,3];
const arr2 = [..arr1]; //[1,2,3]
// MERGE
let fruits = ['🍉', '🍌'];
let vegetables = ['🍆'];
let both = [...fruits, ...vegetables]; // ['🍉', '🍌','🍆']
// REMOVE DUPLICATES
const arr = [5,5,5,6];
const uniqueArr = [...new Set(arr)] //[1,2]
// PASSING AS ARGUMENTS
const arr = [5,6,7,8,9];
const min = Math.min(...arr) //5
// CONVERT STRING TO CHAR
const firstname = 'Emre';
const splitted = [...firstname]; // ['E', 'm', 'r', 'e']
// FILTER
const data = {category: "animals", items: ["dog", "cat", "bird"]};
const {category, ...rest} = data;
console.log(category); // "animals";
console.log(rest); //["dog", "cat", "bird"]
// CONVERTING A NODELIST INTO AN ARRAY
const el = […document.querySelectorAll('div')];
console.log(el); // (3) [div, div, div]
@emreavcilar
/*
A popular interview question for javascript developers is
"How do you swap 2 variables?". Here are 4 ways to swap two numeric variables.
*/
// destructuring assignment
let a=1, b=2;
[a,b] = [b,a];
//temporary variable
let a=1, b=2, temp;
temp = a;
a = b;
b = temp;
//addition and difference
let a=1, b=2;
a = a+b;
b = a-b;
a = a-b;
//bitwiser XOR operator
let a=1, b=2;
a = a^b;
b = b^a;
a = a^b;
/*
JavaScript Tip 💡
Tagged Functions are functions that use template literals to extract their argument.
You might have seen this from styled-components and similar libraries.
It's a more advanced technique, but it’s a great way to streamline certain behavior and workflows.
*/
const logPerson = (msg,name,title) => {
console.log(msg[0] + name + msg[1] + title);
// Do something additional with 'name' and 'age'...
};
const person = {
name: 'Simon',
title: 'dev'
};
// A tagged template is a function call that uses a template literal to extract its arguments.
logPerson `Hi, I'm ${person.name} and I'm a ${person.title}`;
// Hi, I'm Simon and I'ma dev
/*
This snippet can be used to iterate over a callback ntimes.
*/
const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
var output = '';
times(5, i => (output += i));
console.log(output); // 01234
/*
This snippet can be used to find out the time it takes to execute a function.
*/
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
/*
This snippet can be used to format a number like a currency.
*/
const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States)
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local
toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish
/*
create a unique id
*/
export const uid = () => {
const head = Date.now().toString(36);
const tail = Math.random().toString(36).substr(2);
return head + tail;
}
// USAGE
import { uid } from './uid';
const id = uid();
console.log(id); // kvotbxl7jjyl7eis2s
/*
javascript has a native URL() object that parses URL strings into
its different parts. You can also write to properties and generate
a new URL by reading the toString() method.
*/
const url = new URL("http://www.example.com/page?s=value#hash");
url.hash // #hash
url.host // www.example.com
url.hostname // www.example.com
url.href // http://www.example.com/page?s=value#hash
url.origin // http://www.example.com
url.pathname // /page
url.protocol // http:
url.search // ?s=value
url.toString() // full URL
/*
How to access URL parameters with JS!
*/
// URL : localhost/product.html?id=11&name=shoe
const urlSearchParams = window.location.search;
console.log(urlSearchParams);
// everything after "?" will show in console
// including the "?" mark as well -> ?id=11&name=shoe
const params = new URLSearchParams(urlSearchParams);
console.log(params.get('id'));
// -> 11
console.log(params.get('name'));
// -> shoe
console.log(params.get('size'));
// -> null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment