1.2.3 β€’ Published 1 year ago

boost-eo v1.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

BOOST-EO

JSON JavaScriptTypescript Python Shell Git Gitub NPM

BOOST-EO -> Github

πŸ“Œ Description

BOOST-EO is a set of custom code snippets & pattern available for VScode IDE to help you be more productive by providing helper methods πŸš€.


πŸ“Œ Installation

You can install it by typing boost-eo in the extension tab of your IDE


πŸ“Œ Features

  • Javascript snippets collection
  • Javascript patterns collection
  • Some snippets on frequently used javascript libraries
  • Typescript snippets collection
  • Typescript patterns collection
  • React snippets collection (beta)
  • React patterns collection (beta)
  • Python snippets collection
  • Python patterns collection
  • Shell script snippets collection
  • Shell script patterns collection
  • CSS patterns collection (beta)

πŸ“Œ Contribution

🏁 Before contributing, be sure to install all dependencies needed to work in this project by running the following command (in root directory):

npm install

🏁 With each new code snippet added, you need to update all snippets & patterns file and regenerate the documentation, all in one command (in root directory):

npm run build

🏁 You can run a grunt task to make a local backup of this project by running the following command (in root directory):

npm run backups

🏁 Here is a tool that will help you to generate snippets -> https://snippet-generator.app/

🏁 Then you can make a PR.


πŸ“Œ Stats

β—Ύ Total stats

LanguagesPatternsLibrariesSnippets
JavaScript131220
Python000
React18-3
Shell Script0-0
TypeScript0-0
CSS2--

β—Ύ List stats

LanguagesPatternsLibrariesSnippets
JavaScriptarray-1-all array-2-allEqual math-3-approximatelyEqual cast-4-arrayToCSV cast-5-arrayToHtmlList func-6-attempt array-7-average mixte-8-averageBy array-9-bifurcate array-10-bifurcateBy dom-11-bottomVisible cast-12-byteSize string-13-capitalize string-14-capitalizeEveryWord cast-15-castArray array-16-compact array-17-countOccurrences lib-18-createDirIfNotExists bom-19-currentURL date-20-dayOfYear string-21-decapitalize array-22-deepFlatten object-23-default func-24-defer cast-25-degreesToRads array-26-difference mixte-27-differenceBy array-28-differenceWith cast-29-digitize math-30-distance array-31-DropLeft array-32-dropRight array-33-dropRightWhile array-34-dropWhile dom-35-elementContains array-36-Filter Duplicate Elements object-37-findKey array-38-findLast array-39-flatten array-40-forEachRight object-41-forOwn func-42-functionName date-43-Get Time From Date date-44-Get Days Between Dates dom-45-getStyle test-46-getType dom-47-hasClass array-48-head dom-49-hide bom-50-httpsRedirect array-51-indexOfAll array-52-initial dom-53-insertAfter dom-54-insertBefore array-55-intersection array-56-intersectionBy array-57-intersectionWith test-58-is test-59-isAfterDate test-60-isAnagram test-61-isArrayLike test-62-isBeforeDate test-63-isBoolean test-64-isBrowser test-65-isBrowserTabFocused test-66-isLowerCase test-67-isNil test-68-isNull test-69-isNumber test-70-isObject test-71-isObjectLike test-72-isPlainObject test-73-isPromiseLike test-74-isSameDate test-75-isString test-76-isSymbol test-77-isUndefined test-78-isUpperCase test-79-isValidJSON array-80-last object-81-matches date-82-maxDate array-83-maxN date-84-minDate array-85-minN func-86-negate dom-87-nodeListToArray string-88-pad cast-89-radsToDegrees gen-90-randomHexColorCode gen-91-randomIntArrayInRange gen-92-randomIntegerInRange gen-93-randomNumberInRange lib-94-readFileLines bom-95-redirect string-96-reverse math-97-round promise-98-runPromisesInSeries array-99-sample array-100-sampleSize dom-101-scrollToTop string-102-serializeCookie dom-103-setStyle gen-104-shallowClone dom-105-show array-106-shuffle array-107-similarity promise-108-sleep dom-130-smoothScroll string-110-sortCharactersInString cast-111-splitLines dom-112-stripHTMLTags array-113-sum array-114-tail array-115-take array-116-takeRight func-117-timeTaken func-118-times cast-119-toCurrency cast-120-toDecimalMark dom-121-toggleClass date-122-tomorrow func-123-unfold array-124-union array-125-uniqueElements test-126-validateNumber cast-127-words gen-128-getES6moduleSyntaxBySource gen-129-concatJSONsourcesToOneFile test-131-validateEmailfs traversearray basic bom cast class console date destruct dom func gen hybrid math mixte module object regex spread string struct
Python n/a n/a n/a
Reactgen-1-useId state-2-setState jsx-4-confitionals2 comp-5-dataList comp-6-limitedWordTextarea comp-7-accordionItem comp-8-carousel comp-9-collapse comp-10-treeView comp-11-mailTo comp-12-toolTip bbeo-css-pattern-comp-13-ticker bbeo-css-pattern-comp-14-input state-15-propsDrillingState state-15-callbackFuncState event-16-onClick event-17-onChange event-18-onSubmit-gen module version
Shell Script n/a - n/a
TypeScript n/a - n/a
CSStreeviewCSS toolTipCSS--

β—Ύ Patterns triggers categories

LanguagesPatterns
JavaScriptarray - object - func - test (regex) - math - dom - bom - date - cast - mixte - hybrid - string - gen (tools) - lib - promise
Python-
Reactgen - state - jsx - comp (component)
Shell Script-
TypeScript-
CSS-

πŸ“Œ Usage

Snippets & Patterns Index
πŸ”Ž Javascript snippets
πŸ”Ž Javascript patterns
πŸ”Ž Javascript libaries
πŸ”Ž React snippets
πŸ”Ž React patterns
πŸ”Ž CSS patterns

Notation: hybrid = string | array -- mixte = array | object

β—Ύ Javascript snippets

${1:array_var}.sort((${2:a},${3:b}) => ${2:a} - ${3:b})

array: (a0 -> b1) sort in ascending order -> array

${1:array_var}.sort((${2:a},${3:b}) => ${3:b} - ${2:a})

array: (b1 -> a0) sort in descending order -> array

${1:array_var}.slice(${2:start}, ${3:end+1})

array: split an array n, n+1 -> array

${1:array_var}.join(${2:delimiter})

array: join an array from a delimiter to get a string -> string

${1:array_var}.flat(${2:depth})

array: Flatten the elements of a nested array to a specific depth -> array

${1:array_var}.length === 0 ? true : false

array: Check if an array is empty -> boolean

[...new Set(${1:array_var})]

array: Remove duplicates from an array -> array

${1:array_var}.reverse()

array: Reverse all element in an array -> array

if (${1:condition}) {
    ${3:condition_body}
} else if (${2:condition}) {
    ${4:condition_body}
} else {
    ${5:condition_body}
}

basic: Conditional statement

for (let ${1:index} = 0; ${1:index} < ${2:array_length}; ${1:index}++) {
    ${3:for_body}
}

basic: For loop

while (${1:condition}) {
    ${2:while_body}
}

basic: While loop

do {
    ${2:do_body}
} while (${1:condition});

basic: Do while loop

for (let ${1:e} in ${2:array_var}) {
    ${3:for_body}
}

basic: For in loop

for (let ${1:e} of ${2:array_var}) {
    ${3:for_body}
}

basic: For of loop

${2:array_var}.forEach((${1:e}) => {
    ${3:for_body}
});

basic: For each loop

switch (${1:condition}) {
    case ${2:condition_value}:
        ${3:switch_body}
        break;
    case ${4:condition_value}:
        ${5:switch_body}
        break;
    default:
        ${6:switch_body}
        break;
}

basic: Switch statement

try {
    ${1:try_body}
} catch (${2:error}) {
    ${3:catch_body}
}

basic: Try catch statement

try {
    ${1:try_body}
} catch (${2:error}) {
    ${3:catch_body}
} finally {
    ${4:finally_body}
}

basic: Try catch finally statement

try {
    ${1:try_body}
} catch (${2:error}) {
    ${3:catch_body}
} catch (${4:error}) {
    ${5:catch_body}
} finally {
    ${6:finally_body}
}

basic: Try catch finally statement with multiple catch blocks

window.addEventListener(${1:'resize, scroll'}, ${2:callback})

bom: Create window event listener

${1:object}.toString()

cast: method 1 - Convert any object to string -> string

String(${1:object})

cast: method 2 - Convert any object to string -> string

Array.from(${1:string_var})

cast: method 1 - convert string to array -> array

[... ${1:string_var}]

cast: method 2 - convert string to array -> array

${1:string_var}.split``

cast: method 3 - convert string to array -> array

Number(${1:string_var})

cast: method 1 - convert string to number -> number

parseInt(${1:string_var})

cast: method 2 - convert string to number -> number

+('0x'+ ${1:hex_var})

cast: hex -> dec

${1:dec_var}.toString(16)

cast: dec -> hex

parseInt(${1:oct_var}, 8)

cast: oct -> dec

${1:dec_var}.toString(8)

cast: dec -> oct

parseInt(${bin_var}, 2)

cast: bin -> dec

${1:dec_var}.toString(2)

cast: dec -> bin

get ${1:property_name} () { return this.${1:property_name}; }

class: Create getter pattern

set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; }

class: Create setter pattern

${1:method_name} () { ${2:method_body} }

class: Create method pattern

constructor () { ${1:constructor_body} }

class: Create constructor pattern

static ${1:method_name} () { ${2:method_body} }

class: Create static method pattern

static ${1:property_name} = ${2:property_value}

class: Create static property pattern

static get ${1:property_name} () { return this.${1:property_name}; }

class: Create static getter pattern

static set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; }

class: Create static setter pattern

class Circle extends Shape {
  
  // constructor
  constructor (radius) {
    this.radius = radius
  }
  
  // methods
   getArea () {
    return Math.PI * 2 * this.radius
  }
  
  // superclass
   expand (n) {
    return super.expand(n) * Math.PI
  }
  
  //static method
   static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}

class: Generate class pattern

console.log(${1:object})

console: console log

console.error(${1:object})

console: console error

console.table(${1:object})

console: console table

console.info(${1:object})

console: console info

console.warn(${1:object})

console: console warn

const ${1:date_objVar} = new Date()

date: Create a date object (null args)

const ${1:date_objVar} = new Date(${2:year}, ${3:month}, ${4:day}, ${5:hour}, ${6:minute}, ${7:second}, ${8:millisecond})

date: Create a date object (full args)

const ${1:date_objVar} = new Date(${2:date_string})

date: Create a date object (date string)

${1:date_objVar}.now()

date: Get current date

${1:date_objVar}.getDay()

date: Get current day

${1:date_objVar}.getMonth()

date: Get current month

${1:date_objVar}.getFullYear()

date: Get current year

${1:date_objVar}.getHours()

date: Get current hour

${1:date_objVar}.getMinutes()

date: Get current minute

${1:date_objVar}.getSeconds()

date: Get current second

${1:date_objVar}.getMilliseconds()

date: Get current millisecond

${1:date_objVar}.getTime()

date: Get current time

${1:date_objVar}.toString()

date: Get current date as string

${1:date_objVar}.setDate(${2:new_date})

date: Set date

${1:date_objVar}.setMonth(${2:new_month})

date: Set month

${1:date_objVar}.setFullYear(${2:new_year})

date: Set year

${1:date_objVar}.setHours(${2:new_hour})

date: Set hour

${1:date_objVar}.setMinutes(${2:new_minute})

date: Set minute

${1:date_objVar}.setSeconds(${2:new_second})

date: Set second

${1:date_objVar}.setMilliseconds(${2:new_millisecond})

date: Set millisecond

${1:date_objVar}.setTime(${2:new_time})

date: Set time

const [${1:var1}, ${2:var2}] = [${3:value1}, ${4:value2}]

destruct: Destructuring assignment -> array

const {${1:attrib1}, ${2:attrib2}} = ${3:object_container}

destruct: Object destructuring assignment -> object

document.getElementById(${1:id})

dom: Get element by id

document.getElementsByClassName(${1:class})

dom: Get element by class

document.getElementsByTagName(${1:tag})

dom: Get element by tag

document.querySelector(${1:query})

dom: Get element by query

document.querySelectorAll(${1:query})

dom: Get element by query all

document.getElementsByName(${1:name})

dom: Get element by name

document.createElement(${1:tag})

dom: Create html element of tag

document.createTextNode(${1:text})

dom: Create text node

document.getElementById(${1:id}).innerHTML = ${2:html}

dom: Get element by id and set innerHTML

document.getElementById(${1:id}).textContent = ${2:text}

dom: Get element by id and set textContent

document.getElementById(${1:id}).value = ${2:value}

dom: Get element by id and set value

document.getElementById(${1:id}).setAttribute(${2:attribute}, ${3:value})

dom: Get element by id and set attribute

document.getElementById(${1:id}).getAttribute(${2:attribute})

dom: Get element by id and get attribute

document.getElementById(${1:id}).removeAttribute(${2:attribute})

dom: Get element by id and remove attribute

document.getElementById(${1:id}).classList.add(${2:class})

dom: Get element by id and add class

document.getElementById(${1:id}).classList.remove(${2:class})

dom: Get element by id and remove class

document.getElementById(${1:id}).classList.toggle(${2:class})

dom: Get element by id and toggle class

document.getElementById(${1:id}).classList.contains(${2:class})

dom: Get element by id and check class

document.getElementById(${1:id}).appendChild(${2:child})

dom: Get element by id and append child

document.getElementById(${1:id}).removeChild(${2:child})

dom: Get element by id and remove child

document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference})

dom: Get element by id and insert before

document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference}.nextSibling)

dom: Get element by id and insert after

document.getElementById(${1:id}).replaceChild(${2:child}, ${3:reference})

dom: Get element by id and replace child

document.getElementById(${1:id}).childNodes

dom: Get element by id and retrieve all child nodes]

document.getElementById(${1:id}).firstChild

dom: Get element by id and retrieve first child node]

document.getElementById(${1:id}).lastChild

dom: Get element by id and retrieve last child node]

document.getElementById(${1:id}).parentNode

dom: Get element by id and retrieve parent node]

document.getElementById(${1:id}).addEventListener(${2:click, 'keypress, scroll, mouseenter, mouseout, input, submit, load'}, ${3:callback})

dom: Get element by id and add event listener]

${1:e}.target.value

dom: Get target value from event]

document.getElementById(${1:id}).addEventListener(${2:'submit'}, ${3:e} => {
    ${3:e}.preventDefault()
})

dom: Get element by id and add event listener with prevent default]

document.getElementById(${1:id}).addEventListener(${2:click, 'keypress, scroll, mouseenter, mouseout, input, submit, load'}, ${3:e} => {
    ${3:e}.stopPropagation()
})

dom: Get element by id and add event listener with stop propagation]

const ${1:func_name} = (${2:args}) => {
  ${3:code...}
}

func: Create arrow function

[${1:a},${2:b}] = [${2:b},${1:a}]

gen: Swap 2 values ​​from 2 variables

let ${1:id_name} = idMaker()
${1:id_name}.next().value  // β†’ 0
${1:id_name}.next().value  // β†’ 1
${1:id_name}.next().value  // β†’ 2

gen: Id generator

String.fromCharCode(...Array(123).keys()).slice(97)

gen: Alphabet generator

[...Array(${1:min(0)~max(n+1)})].map((_, i) => i); 

gen: Number generator

${1:hybr_var}.indexOf(${2:e})

hybrid: Find index of element

${1:hybr_var}.includes(${2:e})

hybrid: Check the existence of an element

${1:hybr_var}.length

hybrid: Length of string/array

${1:number_var}.toFixed(${2:decal})

math: Format a number in fixed-dot notation -> number

${1:number_var} ** ${2:exp}

math: Power of number

Math.max(... ${1: element})

math: Get MAX element

Math.min(... ${1: element})

math: Get MAX element

Math.log(${solution})/Math.log(${base})

math: Get exponent of a number

Math.sqrt(${1:number})

math: Get square of a number

Math.abs(${1:number})

math: Get absolute value of a number

Math.round(${1:number})

math: Get round value of a number

Math.ceil(${1:number})

math: Get ceil value of a number

Math.floor(${1:number})

math: Get floor value of a number

Math.random()

math: Get random value between 0 and 1

Math.floor(Math.random() * ${1:max})

math: Get random value between 0 and max

Math.floor(Math.random() * (${1:max} - ${2:min}) + ${2:min})

math: Get random value between min and max

Math.PI

math: Get PI value

Math.E

math: Get E value

Math.LN2

math: Get LN2 value

Math.LN10

math: Get LN10 value

${1:mixte_var}.find(${2:e} => ${2:e} ${3:===} ${4:foo})

mixte: Search a specific element -> mixed

${1:mixte_var}.some(${2:e} => ${2:e} ${3:===} ${4:foo})

mixte: Check one or more specific element.s of an array/object (no size modification) -> boolean

${1:mixte_var}.every(${2:e} => ${2:e} ${3:===} ${4:foo})

mixte: Check the integrity of the elements of an array/object (no size modification) -> boolean

${1:mixte_var}.map(${2:e} => {${3:expression}})

mixte: Processing of different element of the array/object (no modification of the size) -> mixed

${1:mixte_var}.filter(${2:e} => {${3:condition}})

mixte: Filter the element of an array/object (size modification) -> mixed

${1:mixte_var}.reduce((${2:total, e}) => {${3:total + e}})

mixte: Processing each element of the array/object to obtain a single value -> number

${1:mixte_var}.fill(${2:start_index},${3:foo})

mixte: Fill an array/object with a static value -> mixed

${1:mixte_var}.forEach((${2:e}) => {
    ${3:expression}
})

mixte: Browse the elements of an array/object -> any

import ${1:module_name} from ${2:module_source};

module: Imports entire module statement in ES6 syntax

import { ${1:module_name} } from ${2:module_source};

module: Imports only a portion of the module in ES6 syntax (destructuring assignment)

Object.values(${1:object_var})

object: Extract objecy values

Object.entries(${1:object_var})

object: Extract object entries

Object.keys(${1:object_var}).length

object: Get object length

${1:string_var}.match(/\d/g);

regex: Extract number in string

const ${1:string_var} = ${2:string_value}
${3:occ_name}=(${1:string_var}.match(/${4:arg}/g)||[]).length 

regex: Get total occurrence of argument in string

${1:string_var}.match(/${2:arg}/)

regex: {arg} must be present from {string_var}

${1:string_var}.match(/^${2:arg}/)

regex: Start of {arg}

${1:string_var}.match(/^${2:arg}/)

regex: End of {arg}

${1:string_var}.match(/${2:a}|${3:b}/)

regex: {a} OR {b} must be present from {string_var}

[...${1:arr1}, ...${2:arr2}]

spread: Merge several arrays (concat() alternative) -> array

{...${1:obj1}, ...${2:obj2}}

spread: Merge several objects (Object.assign() alternative) -> object

[...new Set(${1:array_var})]

spread: Remove duplicates from an array -> array

{...${1:obj_var}, ${2:newProp}: ${3:foo}}

spread: Add a new prop/value to an existing object -> object

${1:string_var}.replace(${2:'input'}, ${3:'output'})

string: Replace single occurrence of value -> string

${1:string_var}.replaceAll(${2:'input'}, ${3:'output'})

string: Replace all occurrences of value -> string

${1:string_var}.split(${2:'delimiter'})

string: Split string into array -> array

${1:string_var}.substr(${2:start}, ${3:end+1})

string: Split a string start, end+1 -> string

${1:string_var}.repeat(${2:N})

string: Repeat a string N times -> string

${1:string_var}.trim()

string: Remove the white space at the beginning and at the end of a string -> string

${1:string_var}.charAt(${2:index})

string: Get chatAt index -> string

${1:string_var}.startsWith(${2:input}, ${3:start_index})

string: Check start of a string -> boolean

${1:string_var}.endsWith(${2:input}, ${3:end_index})

string: Check end of a string -> boolean

${1:string_var}.toLowerCase()

string: String to lower case -> string

${1:string_var}.toUpperCase()

string: String to upper case -> string

${1:array_var}.push(${2:e})

struct: Add to queue -> array

${1:array_var}.unshift(${2:e})

struct: Add to head -> array

${1:array_var}.pop(${2:e})

struct: Delete at tail -> array

${1:array_var}.shift(${2:e})

struct: Delete at head -> array

β—Ύ Javascript patterns

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true

pattern: This snippet returns if the predicate function returns for all elements in a collection and otherwise. You can omit the second argument if you want to use as a default value.

const allEqual = arr => arr.every(val => val === arr[0]);

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true

pattern: This snippet checks whether all elements of the array are equal.

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;

approximatelyEqual(Math.PI / 2.0, 1.5708); // true

pattern: This snippet checks whether two numbers are approximately equal to each other, with a small difference.

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
  
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'```

pattern: This snippet converts the elements to strings with comma-separated values.

const arrayToHtmlList = (arr, listID) =>
  (el => (
    (el = document.querySelector('#' + listID)),
    (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
  ))();
  
arrayToHtmlList(['item 1', 'item 2'], 'myListID');

pattern: This snippet converts the elements of an array into tags and appends them to the list of the given ID.

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 = []

pattern: This snippet executes a function, returning either the result or the caught error object.

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2

pattern: This snippet returns the average of two or more numerical values.

const averageBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
  arr.length;
  
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5

pattern: This snippet returns the average of an array after initially doing the mapping of each element to a value using a given function.

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]

pattern: This snippet splits values into two groups and then puts a truthy element of in the first group, and in the second group otherwise.

const bifurcateBy = (arr, fn) =>
  arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
  
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]

pattern: This snippet splits values into two groups, based on a predicate function. If the predicate function returns a truthy value, the element will be placed in the first group. Otherwise, it will be placed in the second group.

const bottomVisible = () =>
  document.documentElement.clientHeight + window.scrollY >=
  (document.documentElement.scrollHeight || document.documentElement.clientHeight);

bottomVisible(); // true

pattern: This snippet checks whether the bottom of a page is visible.

const byteSize = str => new Blob([str]).size;

byteSize('πŸ˜€'); // 4
byteSize('Hello World'); // 11

pattern: This snippet returns the length of a string in bytes.

const capitalize = ([first, ...rest]) =>
  first.toUpperCase() + rest.join('');
  
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'

pattern: This snippet capitalizes the first letter of a string.

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

capitalizeEveryWord('hello world!'); // 'Hello World!'

pattern: This snippet capitalizes the first letter of every word in a given string.

const castArray = val => (Array.isArray(val) ? val : [val]);

castArray('foo'); // ['foo']
castArray([1]); // [1]

pattern: This snippet converts a non-array value into array.

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
// [ 1, 2, 3, 'a', 's', 34 ]

pattern: This snippet removes false values from an array.

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

pattern: This snippet counts the occurrences of a value in an array.

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

pattern: This snippet uses to check whether a directory exists and then to create it if it doesn’t.

const currentURL = () => window.location.href;

currentURL(); // 'https://medium.com/@fatosmorina'

pattern: This snippet returns the current URL.

const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 272

pattern: This snippet gets the day of the year from a object.

const decapitalize = ([first, ...rest]) =>
  first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar'

pattern: This snippet turns the first letter of a string into lowercase.

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

pattern: This snippet flattens an array recursively.

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);

defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }

pattern: This snippet assigns default values for all properties in an object that are .

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'

pattern: This snippet delays the execution of a function until the current call stack is cleared.

const degreesToRads = deg => (deg * Math.PI) / 180.0;

degreesToRads(90.0); // ~1.5708

pattern: This snippet can be used to convert a value from degrees to radians.

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};

difference([1, 2, 3], [1, 2, 4]); // [3]

pattern: This snippet finds the difference between two arrays.

const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => !s.has(fn(x)));
};

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]

pattern: This snippet returns the difference between two arrays, after applying a given function to each element of both lists.

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); 
// [1, 1.2]

pattern: This snippet removes the values for which the comparator function returns .

const digitize = n => [...`${n}`].map(i => parseInt(i));

digitize(431); // [4, 3, 1]

pattern: This snippet gets a number as input and returns an array of its digits.

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);

distance(1, 1, 2, 3); // 2.23606797749979

pattern: This snippet returns the distance between two points by calculating the Euclidean distance.

const dropLeft = (arr, n = 1) => arr.slice(n);

dropLeft([1, 2, 3]); // [2,3]
dropLeft([1, 2, 3], 2); // [3]
dropLeft([1, 2, 3], 42); // []

pattern: This snippet returns a new array with elements removed from the left.

const dropRight = (arr, n = 1) => arr.slice(0, -n);

dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []

pattern: This snippet returns a new array with elements removed from the right.

const dropRightWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
  return arr;
};

dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]

pattern: This snippet removes elements from the right side of an array until the passed function returns .

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]

pattern: This snippet removes elements from an array until the passed function returns .

const elementContains = (parent, child) => parent !== child && parent.contains(child);

elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false

pattern: This snippet checks whether the parent element contains the child.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]

pattern: This snippet removes duplicate values in an array.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));

findKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  o => o['active']
); // 'barney'

pattern: This snippet returns the first key that satisfies a given function.

const findLast = (arr, fn) => arr.filter(fn).pop();

findLast([1, 2, 3, 4], n => n % 2 === 1); // 3

pattern: This snippet returns the last element for which a given function returns a truthy value.

const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

pattern: This snippet flattens an array up to a specified depth using recursion.

const forEachRight = (arr, callback) =>
  arr
    .slice(0)
    .reverse()
    .forEach(callback);
    
forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'

pattern: This snippet executes a function for each element of an array starting from the array’s last element.

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1

pattern: This snippet iterates on each property of an object and iterates a callback for each one respectively.

const functionName = fn => (console.debug(fn.name), fn);

functionName(Math.max); // max (logged in debug channel of console)

pattern: This snippet prints the name of a function into the console.

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // "08:38:00"

pattern: This snippet can be used to get the time from a object as a string.

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);
  
getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2

pattern: This snippet can be used to find the difference in days between two dates.

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];

getStyle(document.querySelector('p'), 'font-size'); // '16px'

pattern: This snippet can be used to get the value of a CSS rule for a particular element.

const getType = v =>
  v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
  
getType(new Set([1, 2, 3])); // 'set'

pattern: This snippet can be used to get the type of a value.

const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true

pattern: This snippet checks whether an element has a particular class.

const head = arr => arr[0];

head([1, 2, 3]); // 1

pattern: This snippet returns the of a list.

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

hide(document.querySelectorAll('img')); // Hides all <img> elements on the page

pattern: This snippet can be used to hide all elements specified.

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

pattern: This snippet can be used to redirect from HTTP to HTTPS in a particular domain.

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []

pattern: This snippet can be used to get all indexes of a value in an array, which returns an empty array, in case this value is not included in it.

const initial = arr => arr.slice(0, -1);

initial([1, 2, 3]); // [1,2]const initial = arr => arr.slice(0, -1);
initial([1, 2, 3]); // [1,2]

pattern: This snippet returns all elements of an array except the last one.

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);

insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>

pattern: This snippet can be used to insert an HTML string after the end of a particular element.

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);

insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>

pattern: This snippet can be used to insert an HTML string before a particular element.

const intersection = (a, b) => {
  const s = new Set(b);
  return a.filter(x => s.has(x));
};

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

pattern: This snippet can be used to get an array with elements that are included in two other arrays.

const intersectionBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => s.has(fn(x)));
};

intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]

pattern: This snippet can be used to return a list of elements that exist in both arrays, after a particular function has been executed to each element of both arrays.

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);

intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]

pattern: This snippet can be used to return a list of elements that exist in both arrays by using a comparator function.

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

pattern: This snippet can be used to check if a value is of a particular type.

const isAfterDate = (dateA, dateB) => dateA > dateB;

isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true

pattern: This snippet can be used to check whether a date is after another date.

const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};

isAnagram('iceman', 'cinema'); // true

pattern: This snippet can be used to check whether a particular string is an anagram with another string.

const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';

isArrayLike(document.querySelectorAll('.className')); // true
isArrayLike('abc'); // true
isArrayLike(null); // false

pattern: This snippet can be used to check if a provided argument is iterable like an array.

const isBeforeDate = (dateA, dateB) => dateA < dateB;

isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true

pattern: This snippet can be used to check whether a date is before another date.

const isBoolean = val => typeof val === 'boolean';

isBoolean(null); // false
isBoolean(false); // true

pattern: This snippet can be used to check whether an argument is a boolean.

const isBrowser = () => ![typeof window, typeof document].includes('undefined');

isBrowser(); // true (browser)
isBrowser(); // false (Node)

pattern: 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 isBrowserTabFocused = () => !document.hidden;

isBrowserTabFocused(); // true

pattern: This snippet can be used to determine whether the browser tab is focused.

const isLowerCase = str => str === str.toLowerCase();

isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false

pattern: This snippet can be used to determine whether a string is lower case.

const isNil = val => val === undefined || val === null;

isNil(null); // true
isNil(undefined); // true

pattern: This snippet can be used to check whether a value is or .

const isNull = val => val === null;

isNull(null); // true

pattern: This snippet can be used to check whether a value is .

const isNumber = val => typeof val === 'number';

isNumber('1'); // false
isNumber(1); // true

pattern: This snippet can be used to check whether a provided value is a number.

const isObject = obj => obj === Object(obj);

isObject([1, 2, 3, 4]); // true
isObject([]); // true
isObject(['Hello!']); // true
isObject({ a: 1 }); // true
isObject({}); // true
isObject(true); // false

pattern: This snippet can be used to check whether a provided value is an object. It uses the Object constructor to create an object wrapper for the given value.

const isObjectLike = val => val !== null && typeof val === 'object';

isObjectLike({}); // true
isObjectLike(