Skip to content

Instantly share code, notes, and snippets.

@pcast01
Forked from hk-skit/js-oneliner.js
Last active April 28, 2019 15:10
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 pcast01/b56739f0fe868334cfebc6cbbfba30ca to your computer and use it in GitHub Desktop.
Save pcast01/b56739f0fe868334cfebc6cbbfba30ca to your computer and use it in GitHub Desktop.
Useful Array One-liners and other js tips
// Remove Duplicates from an array
const removeDuplicates =
arr => arr.filter((item, index) => index === arr.indexOf(item));
const removeDuplicates1 = array => [...new Set(array)];
const removeDuplicates2 = array => Array.from(new Set(array));
// Flattens an array(doesn't flatten deeply).
const flatten = array => [].concat(...array);
const flattenDeep =
arr => arr.reduce((fArr, item) =>
fArr.concat(Array.isArray(item) ? flatten(item) : item), []);
// Merge arrays
const merge = (...arrays) => [].concat(...arrays);
// Pipe fn
const pipe = (...fns) => arg => fns.reduce((v, fn) => fn(v), arg);
// Generates range [start, end) with step
const range = (start, end, step = 1) =>
Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step);
// Generates random hex color code.
const color = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16);
// Get unique values in array
var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
//Array and Boolean
//Ever need to filter falsy values (0, undefined, null, false, etc.) out of an array? You may not have known this trick:
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(Boolean);
//Create Empty Objects
//Sure you can create an object that seems empty with {}, but that object still has a __proto__ and the usual hasOwnProperty and other object methods. There is a way, however, to create a pure "dictionary" object:
let dict = Object.create(null);
// dict.__proto__ === "undefined"
// No object properties exist until you add them
//Merge Objects
//The need to merge multiple objects in JavaScript has been around forever, especially as we started creating classes and widgets with options:
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };
const summary = {...person, ...tools, ...attributes};
/*
Object {
"computer": "Mac",
"editor": "Atom",
"eyes": "Blue",
"gender": "Male",
"hair": "Brown",
"handsomeness": "Extreme",
"name": "David Walsh",
}
*/
//Require Function Parameters
//Being able to set default values for function arguments was an awesome addition to JavaScript, but check out this trick for requiring values be passed for a given argument:
const isRequired = () => { throw new Error('param is required'); };
const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
// This will throw an error because no name is provided
hello();
// This will also throw an error
hello(undefined);
// These are good!
hello(null);
hello('David');
//Destructuring Aliases
//Destructuring is a very welcomed addition to JavaScript but sometimes we'd prefer to refer to those properties by another name, so we can take advantage of aliases:
const obj = { x: 1 };
// Grabs obj.x as { x }
const { x } = obj;
// Grabs obj.x as as { otherName }
const { x: otherName } = obj;
//Get Query String Parameters
//For years we wrote gross regular expressions to get query string values but those days are gone -- enter the amazing URLSearchParams API:
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment