Skip to content

Instantly share code, notes, and snippets.

@sixertoy
Last active April 23, 2023 22:35
Show Gist options
  • Save sixertoy/c70b07f2740abbc3015334892aacbc64 to your computer and use it in GitHub Desktop.
Save sixertoy/c70b07f2740abbc3015334892aacbc64 to your computer and use it in GitHub Desktop.
ES6 Tips & Tricks

JavaScript Tips

Yarn/NPM

Reorder package.json

npx sort-package-json

Array

Object

  • Has Property

Console

  • Colors
  • Emit beep
  • Percent Preloader

Files/Directories

  • Ensure directory exists

Promise

  • Delayed

String

  • Capitalize
  • Slugify

Functional

  • Compose

NodeJS

  • Quick Local IP
// Arguments to Array
const args = [...arguments];
// NodeList to Array (short)
const nodelistToArray = [...document.querySelectorAll('div')];
// NodeList to Array
const nodelistToArray = elts =>
[].slice.(elts).map(item => {});
// Remove dulicate entries
const unique = entries =>
entries.filter((elem, pos, arr) => arr.indexOf(elem) === pos);
// Remove dulicate entries
const unique = entries => [...new Set(entries)];
// Returns key values in an array of object
const pluck = (arr, key) => arr.map(obj => obj[key]);
// Flatten array
const flatten = arr =>
Array.prototype.concat.apply([], arr);
// Returns max values in an array
const max = arr => Math.max(...arr);
// Fill an array with `n` values
const filln = (n) =>
Array.from(Array(n).keys());
// Emit a beep
function beepNow = () =>
process.stdout.write('\x07');
// Colors in console
// source: http://misc.flogisoft.com/bash/tip_colors_and_formatting
const colorize = (message, color) => {
const getcolor = (msg, code) => `\x1b[${code}m${msg}\x1b[39m`;
switch (color) {
case 'white':
return getcolor(message, 37);
case 'cyan':
return getcolor(message, 36);
case 'magenta':
return getcolor(message, 35);
case 'blue':
return getcolor(message, 34);
case 'yellow':
return getcolor(message, 33);
case 'green':
return getcolor(message, 32);
case 'red':
return getcolor(message, 31);
case 'black':
return getcolor(message, 30);
case 'grey':
case 'gray':
default:
return getcolor(message, 90);
}
};
// Percent Preloader
const preloader = (count, total) => {
const percent = (total <= 0) ? 0
: Math.round(((count * 100) / total) * 10) / 10;
process.stdout.write(`\r> loading... ${percent}%`);
}
// Ensure directory exists
const ensureDirSync = (directory) =>
fs.existsSync(directory) || fs.mkdirSync(directory);
function floatRange(min, max, float) {
const floating = Math.pow(10, float);
let factors = [];
let floatmin = min * floating;
const floatmax = max * floating;
while (floatmin < floatmax) {
floatmin = floatmin + 1;
factors.push(floatmin);
}
return factors.map(ratio => ratio / floating);
}
// FILO
const compose = (...fns) => fns.reverse()
.reduce((prev, next) => value => next(prev(value)), value => value);
// FIFO
const pipe = (...fns) =>
compose.apply(compose, fns.reverse());
const log2 = n => Math.log(n) / Math.log(2);
// get local ip
const os = require('os');
const dns = require('dns');
const hostname = os.hostname();
dns.lookup(hostname, (err, add) => {
console.log('Local IP', add);
});
# Has Property
const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
// delay a promise
return new Promise(resolve => setTimeout(resolve, 5000));
// Capitalize
const capitalize = (str) =>
`${str.charAt(0).toUpperCase()}${str.slice(1)}`;
// Slugify
// Source: https://gist.github.com/mathewbyrne/1280286
const slugify = (text) => {
const a = 'àáäâèéëêìíïîòóöôùúüûñçßÿœæŕśńṕẃǵǹḿǘẍźḧ·/_,:;';
const b = 'aaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------';
const p = new RegExp(a.split('').join('|'), 'g');
return text.toString().toLowerCase()
.replace(/\s+/g, '-')
.replace(p, c => b.charAt(a.indexOf(c)))
.replace(/&/g, '-and-')
.replace(/[^\w-]+/g, '')
.replace(/--+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
};
@sixertoy
Copy link
Author

sixertoy commented May 17, 2017

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment