🏁 Then you can make a PR.
prefix |
body |
description |
bbeo-js-array-ascElement
|
${1:array_var}.sort((${2:a},${3:b}) => ${2:a} - ${3:b})
|
[array]: (a0 -> b1) sort in ascending order -> array
|
bbeo-js-array-descElement
|
${1:array_var}.sort((${2:a},${3:b}) => ${3:b} - ${2:a})
|
[array]: (b1 -> a0) sort in descending order -> array
|
bbeo-js-array-slice
|
${1:array_var}.slice(${2:start}, ${3:end+1})
|
[array]: split an array [n, n+1] -> array
|
bbeo-js-array-join
|
${1:array_var}.join(${2:delimiter})
|
[array]: join an array from a delimiter to get a string -> string
|
bbeo-js-array-flat
|
${1:array_var}.flat(${2:depth})
|
[array]: Flatten the elements of a nested array to a specific depth -> array
|
bbeo-js-array-isEmpty
|
${1:array_var}.length === 0 ? true : false
|
[array]: Check if an array is empty -> boolean
|
bbeo-array-js-removeDuplicates
|
[...new Set(${1:array_var})]
|
[array]: Remove duplicates from an array -> array
|
bbeo-js-array-reverse
|
${1:array_var}.reverse()
|
[array]: Reverse all element in an array -> array
|
bbeo-js-basic-ifCondition
|
if (${1:condition}) {
${3:condition_body}
} else if (${2:condition}) {
${4:condition_body}
} else {
${5:condition_body}
}
|
[basic]: Conditional statement
|
bbeo-js-basic-forLoop
|
for (let ${1:index} = 0; ${1:index} < ${2:array_length}; ${1:index}++) {
${3:for_body}
}
|
[basic]: For loop
|
bbeo-js-basic-whileLoop
|
while (${1:condition}) {
${2:while_body}
}
|
[basic]: While loop
|
bbeo-js-basic-doWhileLoop
|
do {
${2:do_body}
} while (${1:condition});
|
[basic]: Do while loop
|
bbeo-js-basic-forInLoop
|
for (let ${1:e} in ${2:array_var}) {
${3:for_body}
}
|
[basic]: For in loop
|
bbeo-js-basic-forOfLoop
|
for (let ${1:e} of ${2:array_var}) {
${3:for_body}
}
|
[basic]: For of loop
|
bbeo-js-basic-forEachLoop
|
${2:array_var}.forEach((${1:e}) => {
${3:for_body}
});
|
[basic]: For each loop
|
bbeo-js-basic-switchStatement
|
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
|
bbeo-js-basic-tryCatchStatement
|
try {
${1:try_body}
} catch (${2:error}) {
${3:catch_body}
}
|
[basic]: Try catch statement
|
bbeo-js-basic-tryCatchFinallyStatement
|
try {
${1:try_body}
} catch (${2:error}) {
${3:catch_body}
} finally {
${4:finally_body}
}
|
[basic]: Try catch finally statement
|
bbeo-js-basic-tryCatchFinallyStatementMultiple
|
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
|
bbeo-js-bom-addWindowEventListener
|
window.addEventListener(${1:'resize, scroll'}, ${2:callback})
|
[bom]: Create window event listener
|
bbeo-js-cast-objToString1
|
${1:object}.toString()
|
[cast]: method 1 - Convert any object to string -> string
|
bbeo-js-cast-objToString2
|
String(${1:object})
|
[cast]: method 2 - Convert any object to string -> string
|
bbeo-js-cast-stringToArray1
|
Array.from(${1:string_var})
|
[cast]: method 1 - convert string to array -> array
|
bbeo-js-cast-stringToArray2
|
[... ${1:string_var}]
|
[cast]: method 2 - convert string to array -> array
|
bbeo-js-cast-stringToArray3
|
${1:string_var}.split``
|
[cast]: method 3 - convert string to array -> array
|
bbeo-js-cast-stringToNumber1
|
Number(${1:string_var})
|
[cast]: method 1 - convert string to number -> number
|
bbeo-js-cast-stringToNumber2
|
parseInt(${1:string_var})
|
[cast]: method 2 - convert string to number -> number
|
bbeo-js-cast-hex2dec
|
+('0x'+ ${1:hex_var})
|
[cast]: hex -> dec
|
bbeo-js-cast-dec2hex
|
${1:dec_var}.toString(16)
|
[cast]: dec -> hex
|
bbeo-js-cast-oct2dec
|
parseInt(${1:oct_var}, 8)
|
[cast]: oct -> dec
|
bbeo-js-cast-dec2oct
|
${1:dec_var}.toString(8)
|
[cast]: dec -> oct
|
bbeo-js-cast-bin2dec
|
parseInt(${bin_var}, 2)
|
[cast]: bin -> dec
|
bbeo-js-cast-dec2bin
|
${1:dec_var}.toString(2)
|
[cast]: dec -> bin
|
bbeo-js-class-getter
|
get ${1:property_name} () { return this.${1:property_name}; }
|
[class]: Create getter pattern
|
bbeo-js-class-setter
|
set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; }
|
[class]: Create setter pattern
|
bbeo-js-class-method
|
${1:method_name} () { ${2:method_body} }
|
[class]: Create method pattern
|
bbeo-js-class-constructor
|
constructor () { ${1:constructor_body} }
|
[class]: Create constructor pattern
|
bbeo-js-class-staticMethod
|
static ${1:method_name} () { ${2:method_body} }
|
[class]: Create static method pattern
|
bbeo-js-class-staticProperty
|
static ${1:property_name} = ${2:property_value}
|
[class]: Create static property pattern
|
bbeo-js-class-staticGetter
|
static get ${1:property_name} () { return this.${1:property_name}; }
|
[class]: Create static getter pattern
|
bbeo-js-class-staticSetter
|
static set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; }
|
[class]: Create static setter pattern
|
bbeo-js-class-genClassPattern
|
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
|
bbeo-js-console-clg
|
console.log(${1:object})
|
[console]: console log
|
bbeo-js-console-clr
|
console.error(${1:object})
|
[console]: console error
|
bbeo-js-console-clt
|
console.table(${1:object})
|
[console]: console table
|
bbeo-js-console-cli
|
console.info(${1:object})
|
[console]: console info
|
bbeo-js-console-clw
|
console.warn(${1:object})
|
[console]: console warn
|
bbeo-js-date-createNullDate
|
const ${1:date_objVar} = new Date()
|
[date]: Create a date object (null args)
|
bbeo-js-date-createFullDate
|
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)
|
bbeo-js-date-createStringDate
|
const ${1:date_objVar} = new Date(${2:date_string})
|
[date]: Create a date object (date string)
|
bbeo-js-date-now
|
${1:date_objVar}.now()
|
[date]: Get current date
|
bbeo-js-date-day
|
${1:date_objVar}.getDay()
|
[date]: Get current day
|
bbeo-js-date-month
|
${1:date_objVar}.getMonth()
|
[date]: Get current month
|
bbeo-js-date-year
|
${1:date_objVar}.getFullYear()
|
[date]: Get current year
|
bbeo-js-date-hour
|
${1:date_objVar}.getHours()
|
[date]: Get current hour
|
bbeo-js-date-minute
|
${1:date_objVar}.getMinutes()
|
[date]: Get current minute
|
bbeo-js-date-second
|
${1:date_objVar}.getSeconds()
|
[date]: Get current second
|
bbeo-js-date-millisecond
|
${1:date_objVar}.getMilliseconds()
|
[date]: Get current millisecond
|
bbeo-js-date-time
|
${1:date_objVar}.getTime()
|
[date]: Get current time
|
bbeo-js-date-toString
|
${1:date_objVar}.toString()
|
[date]: Get current date as string
|
bbeo-js-date-setDate
|
${1:date_objVar}.setDate(${2:new_date})
|
[date]: Set date
|
bbeo-js-date-setMonth
|
${1:date_objVar}.setMonth(${2:new_month})
|
[date]: Set month
|
bbeo-js-date-setYear
|
${1:date_objVar}.setFullYear(${2:new_year})
|
[date]: Set year
|
bbeo-js-date-setHour
|
${1:date_objVar}.setHours(${2:new_hour})
|
[date]: Set hour
|
bbeo-js-date-setMinute
|
${1:date_objVar}.setMinutes(${2:new_minute})
|
[date]: Set minute
|
bbeo-js-date-setSecond
|
${1:date_objVar}.setSeconds(${2:new_second})
|
[date]: Set second
|
bbeo-js-date-setMillisecond
|
${1:date_objVar}.setMilliseconds(${2:new_millisecond})
|
[date]: Set millisecond
|
bbeo-js-date-setTime
|
${1:date_objVar}.setTime(${2:new_time})
|
[date]: Set time
|
bbeo-js-destruct-assignArray
|
const [${1:var1}, ${2:var2}] = [${3:value1}, ${4:value2}]
|
[destruct]: Destructuring assignment -> array
|
bbeo-js-destruct-assignObject
|
const {${1:attrib1}, ${2:attrib2}} = ${3:object_container}
|
[destruct]: Object destructuring assignment -> object
|
bbeo-js-dom-id
|
document.getElementById(${1:id})
|
[dom]: Get element by id
|
bbeo-js-dom-class
|
document.getElementsByClassName(${1:class})
|
[dom]: Get element by class
|
bbeo-js-dom-tag
|
document.getElementsByTagName(${1:tag})
|
[dom]: Get element by tag
|
bbeo-js-dom-query
|
document.querySelector(${1:query})
|
[dom]: Get element by query
|
bbeo-js-dom-queryAll
|
document.querySelectorAll(${1:query})
|
[dom]: Get element by query all
|
bbeo-js-dom-name
|
document.getElementsByName(${1:name})
|
[dom]: Get element by name
|
bbeo-js-dom-createHTMLElement
|
document.createElement(${1:tag})
|
[dom]: Create html element of tag
|
bbeo-js-dom-createTextNode
|
document.createTextNode(${1:text})
|
[dom]: Create text node
|
bbeo-js-dom-id-innerHTML
|
document.getElementById(${1:id}).innerHTML = ${2:html}
|
[dom]: Get element by id and set innerHTML
|
bbeo-js-dom-id-textContent
|
document.getElementById(${1:id}).textContent = ${2:text}
|
[dom]: Get element by id and set textContent
|
bbeo-js-dom-id-value
|
document.getElementById(${1:id}).value = ${2:value}
|
[dom]: Get element by id and set value
|
bbeo-js-dom-id-attribute
|
document.getElementById(${1:id}).setAttribute(${2:attribute}, ${3:value})
|
[dom]: Get element by id and set attribute
|
bbeo-js-dom-id-getAttribute
|
document.getElementById(${1:id}).getAttribute(${2:attribute})
|
[dom]: Get element by id and get attribute
|
bbeo-js-dom-id-removeAttribute
|
document.getElementById(${1:id}).removeAttribute(${2:attribute})
|
[dom]: Get element by id and remove attribute
|
bbeo-js-dom-id-addClass
|
document.getElementById(${1:id}).classList.add(${2:class})
|
[dom]: Get element by id and add class
|
bbeo-js-dom-id-removeClass
|
document.getElementById(${1:id}).classList.remove(${2:class})
|
[dom]: Get element by id and remove class
|
bbeo-js-dom-id-toggleClass
|
document.getElementById(${1:id}).classList.toggle(${2:class})
|
[dom]: Get element by id and toggle class
|
bbeo-js-dom-id-hasClass
|
document.getElementById(${1:id}).classList.contains(${2:class})
|
[dom]: Get element by id and check class
|
bbeo-js-dom-id-appendChild
|
document.getElementById(${1:id}).appendChild(${2:child})
|
[dom]: Get element by id and append child
|
bbeo-js-dom-id-removeChild
|
document.getElementById(${1:id}).removeChild(${2:child})
|
[dom]: Get element by id and remove child
|
bbeo-js-dom-id-insertBefore
|
document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference})
|
[dom]: Get element by id and insert before
|
bbeo-js-dom-id-insertAfter
|
document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference}.nextSibling)
|
[dom]: Get element by id and insert after
|
bbeo-js-dom-id-replaceChild
|
document.getElementById(${1:id}).replaceChild(${2:child}, ${3:reference})
|
[dom]: Get element by id and replace child
|
bbeo-js-dom-id-childNodes
|
document.getElementById(${1:id}).childNodes
|
[dom]: Get element by id and retrieve all child nodes]
|
bbeo-js-dom-id-firstChild
|
document.getElementById(${1:id}).firstChild
|
[dom]: Get element by id and retrieve first child node]
|
bbeo-js-dom-id-lastChild
|
document.getElementById(${1:id}).lastChild
|
[dom]: Get element by id and retrieve last child node]
|
bbeo-js-dom-id-parentNode
|
document.getElementById(${1:id}).parentNode
|
[dom]: Get element by id and retrieve parent node]
|
bbeo-js-dom-id-addEventListener
|
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]
|
bbeo-js-dom-eventTargetValue
|
${1:e}.target.value
|
[dom]: Get target value from event]
|
bbeo-js-dom-id-addEventListenerWithpreventDefault
|
document.getElementById(${1:id}).addEventListener(${2:'submit'}, ${3:e} => {
${3:e}.preventDefault()
})
|
[dom]: Get element by id and add event listener with prevent default]
|
bbeo-js-dom-id-addEventListenerWithstopPropagation
|
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]
|
bbeo-js-func-arrowFunc
|
const ${1:func_name} = (${2:args}) => {
${3:code...}
}
|
[func]: Create arrow function
|
bbeo-js-gen-permut
|
[${1:a},${2:b}] = [${2:b},${1:a}]
|
[gen]: Swap 2 values from 2 variables
|
bbeo-js-gen-idGen
|
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
|
bbeo-js-gen-alphaGen
|
String.fromCharCode(...Array(123).keys()).slice(97)
|
[gen]: Alphabet generator
|
bbeo-js-gen-numGen
|
[...Array(${1:min(0)~max(n+1)})].map((_, i) => i);
|
[gen]: Number generator
|
bbeo-js-hybrid-indexOfElement
|
${1:hybr_var}.indexOf(${2:e})
|
[hybrid]: Find index of element
|
bbeo-js-hybrid-includesElement
|
${1:hybr_var}.includes(${2:e})
|
[hybrid]: Check the existence of an element
|
bbeo-js-hybrid-length
|
${1:hybr_var}.length
|
[hybrid]: Length of string/array
|
bbeo-js-math-dot
|
${1:number_var}.toFixed(${2:decal})
|
[math]: Format a number in fixed-dot notation -> number
|
bbeo-js-math-pow
|
${1:number_var} ** ${2:exp}
|
[math]: Power of number
|
bbeo-js-math-max
|
Math.max(... ${1: element})
|
[math]: Get MAX element
|
bbeo-js-math-min
|
Math.min(... ${1: element})
|
[math]: Get MAX element
|
bbeo-js-math-expOfNumber
|
Math.log(${solution})/Math.log(${base})
|
[math]: Get exponent of a number
|
bbeo-js-math-sqrt
|
Math.sqrt(${1:number})
|
[math]: Get square of a number
|
bbeo-js-math-abs
|
Math.abs(${1:number})
|
[math]: Get absolute value of a number
|
bbeo-js-math-round
|
Math.round(${1:number})
|
[math]: Get round value of a number
|
bbeo-js-math-ceil
|
Math.ceil(${1:number})
|
[math]: Get ceil value of a number
|
bbeo-js-math-floor
|
Math.floor(${1:number})
|
[math]: Get floor value of a number
|
bbeo-js-math-random
|
Math.random()
|
[math]: Get random value between 0 and 1
|
bbeo-js-math-random-max
|
Math.floor(Math.random() * ${1:max})
|
[math]: Get random value between 0 and max
|
bbeo-js-math-random-minMax
|
Math.floor(Math.random() * (${1:max} - ${2:min}) + ${2:min})
|
[math]: Get random value between min and max
|
bbeo-js-math-pi
|
Math.PI
|
[math]: Get PI value
|
bbeo-js-math-e
|
Math.E
|
[math]: Get E value
|
bbeo-js-math-ln2
|
Math.LN2
|
[math]: Get LN2 value
|
bbeo-js-math-ln10
|
Math.LN10
|
[math]: Get LN10 value
|
bbeo-js-mixte-findElement
|
${1:mixte_var}.find(${2:e} => ${2:e} ${3:===} ${4:foo})
|
[mixte]: Search a specific element -> mixed
|
bbeo-js-mixte-someElement
|
${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
|
bbeo-js-mixte-everyElement
|
${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
|
bbeo-js-mixte-mapElement
|
${1:mixte_var}.map(${2:e} => {${3:expression}})
|
[mixte]: Processing of different element of the array/object (no modification of the size) -> mixed
|
bbeo-js-mixte-filterElement
|
${1:mixte_var}.filter(${2:e} => {${3:condition}})
|
[mixte]: Filter the element of an array/object (size modification) -> mixed
|
bbeo-js-mixte-reduceElement
|
${1:mixte_var}.reduce((${2:total, e}) => {${3:total + e}})
|
[mixte]: Processing each element of the array/object to obtain a single value -> number
|
bbeo-js-mixte-fillElement
|
${1:mixte_var}.fill(${2:start_index},${3:foo})
|
[mixte]: Fill an array/object with a static value -> mixed
|
bbeo-js-mixte-foreachElement
|
${1:mixte_var}.forEach((${2:e}) => {
${3:expression}
})
|
[mixte]: Browse the elements of an array/object -> any
|
bbeo-js-module-imp
|
import ${1:module_name} from ${2:module_source};
|
[module]: Imports entire module statement in ES6 syntax
|
bbeo-js-module-imd
|
import { ${1:module_name} } from ${2:module_source};
|
[module]: Imports only a portion of the module in ES6 syntax (destructuring assignment)
|
bbeo-js-object-extractValues
|
Object.values(${1:object_var})
|
[object]: Extract objecy values
|
bbeo-js-object-extractEntries
|
Object.entries(${1:object_var})
|
[object]: Extract object entries
|
bbeo-js-object-length
|
Object.keys(${1:object_var}).length
|
[object]: Get object length
|
bbeo-js-regex-numExtract
|
${1:string_var}.match(/\d/g);
|
[regex]: Extract number in string
|
bbeo-js-regex-occTotal
|
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
|
bbeo-js-regex-ifExist
|
${1:string_var}.match(/${2:arg}/)
|
[regex]: {arg} must be present from {string_var}
|
bbeo-js-regex-startOf
|
${1:string_var}.match(/^${2:arg}/)
|
[regex]: Start of {arg}
|
bbeo-js-regex-endOf
|
${1:string_var}.match(/^${2:arg}/)
|
[regex]: End of {arg}
|
bbeo-js-regex-ifExistOR
|
${1:string_var}.match(/${2:a}|${3:b}/)
|
[regex]: {a} OR {b} must be present from {string_var}
|
bbeo-spread-mergeArrays
|
[...${1:arr1}, ...${2:arr2}]
|
[spread]: Merge several arrays (concat() alternative) -> array
|
bbeo-spread-mergeObjects
|
{...${1:obj1}, ...${2:obj2}}
|
[spread]: Merge several objects (Object.assign() alternative) -> object
|
bbeo-spread-removeDuplicates
|
[...new Set(${1:array_var})]
|
[spread]: Remove duplicates from an array -> array
|
bbeo-spread-addProp
|
{...${1:obj_var}, ${2:newProp}: ${3:foo}}
|
[spread]: Add a new prop/value to an existing object -> object
|
bbeo-js-string-replace
|
${1:string_var}.replace(${2:'input'}, ${3:'output'})
|
[string]: Replace single occurrence of value -> string
|
bbeo-js-string-replaceAll
|
${1:string_var}.replaceAll(${2:'input'}, ${3:'output'})
|
[string]: Replace all occurrences of value -> string
|
bbeo-js-string-split
|
${1:string_var}.split(${2:'delimiter'})
|
[string]: Split string into array -> array
|
bbeo-js-string-sub
|
${1:string_var}.substr(${2:start}, ${3:end+1})
|
[string]: Split a string [start, end+1] -> string
|
bbeo-js-string-repeat
|
${1:string_var}.repeat(${2:N})
|
[string]: Repeat a string N times -> string
|
bbeo-js-string-trim
|
${1:string_var}.trim()
|
[string]: Remove the white space at the beginning and at the end of a string -> string
|
bbeo-js-string-charAt
|
${1:string_var}.charAt(${2:index})
|
[string]: Get chatAt index -> string
|
bbeo-js-string-startsWith
|
${1:string_var}.startsWith(${2:input}, ${3:start_index})
|
[string]: Check start of a string -> boolean
|
bbeo-js-string-endsWith
|
${1:string_var}.endsWith(${2:input}, ${3:end_index})
|
[string]: Check end of a string -> boolean
|
bbeo-js-string-toLowerCase
|
${1:string_var}.toLowerCase()
|
[string]: String to lower case -> string
|
bbeo-js-string-toUpperCase
|
${1:string_var}.toUpperCase()
|
[string]: String to upper case -> string
|
bbeo-js-struct-addToQueue
|
${1:array_var}.push(${2:e})
|
[struct]: Add to queue -> array
|
bbeo-js-struct-addToHead
|
${1:array_var}.unshift(${2:e})
|
[struct]: Add to head -> array
|
bbeo-js-struct-deleteAtTail
|
${1:array_var}.pop(${2:e})
|
[struct]: Delete at tail -> array
|
bbeo-js-struct-deleteAtHead
|
${1:array_var}.shift(${2:e})
|
[struct]: Delete at head -> array
|
prefix |
body |
description |
bbeo-js-pattern-array-1-all
|
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.
|
bbeo-js-pattern-array-2-allEqual
|
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.
|
bbeo-js-pattern-math-3-approximatelyEqual
|
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.
|
bbeo-js-pattern-cast-4-arrayToCSV
|
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.
|
bbeo-js-pattern-cast-5-arrayToHtmlList
|
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.
|
bbeo-js-pattern-func-6-attempt
|
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.
|
bbeo-js-pattern-array-7-average
|
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.
|
bbeo-js-pattern-mixte-8-averageBy
|
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.
|
bbeo-js-pattern-array-9-bifurcate
|
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.
|
bbeo-js-pattern-array-10-bifurcateBy
|
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.
|
bbeo-js-pattern-dom-11-bottomVisible
|
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.
|
bbeo-js-pattern-cast-12-byteSize
|
const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11
|
[pattern]: This snippet returns the length of a string in bytes.
|
bbeo-js-pattern-string-13-capitalize
|
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.
|
bbeo-js-pattern-string-14-capitalizeEveryWord
|
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.
|
bbeo-js-pattern-cast-15-castArray
|
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]
|
[pattern]: This snippet converts a non-array value into array.
|
bbeo-js-pattern-array-16-compact
|
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.
|
bbeo-js-pattern-array-17-countOccurrences
|
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.
|
bbeo-js-pattern-lib-18-createDirIfNotExists
|
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.
|
bbeo-js-pattern-bom-19-currentURL
|
const currentURL = () => window.location.href;
currentURL(); // 'https://medium.com/@fatosmorina'
|
[pattern]: This snippet returns the current URL.
|
bbeo-js-pattern-date-20-dayOfYear
|
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.
|
bbeo-js-pattern-string-21-decapitalize
|
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.
|
bbeo-js-pattern-array-22-deepFlatten
|
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.
|
bbeo-js-pattern-object-23-default
|
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 .
|
bbeo-js-pattern-func-24-defer
|
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.
|
bbeo-js-pattern-cast-25-degreesToRads
|
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.
|
bbeo-js-pattern-array-26-difference
|
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.
|
bbeo-js-pattern-mixte-27-differenceBy
|
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.
|
bbeo-js-pattern-array-28-differenceWith
|
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 .
|
bbeo-js-pattern-cast-29-digitize
|
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.
|
bbeo-js-pattern-math-30-distance
|
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.
|
bbeo-js-pattern-array-31-DropLeft
|
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.
|
bbeo-js-pattern-array-32-dropRight
|
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.
|
bbeo-js-pattern-array-33-dropRightWhile
|
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 .
|
bbeo-js-pattern-array-34-dropWhile
|
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 .
|
bbeo-js-pattern-dom-35-elementContains
|
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.
|
bbeo-js-pattern-array-36-Filter Duplicate Elements
|
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.
|
bbeo-js-pattern-object-37-findKey
|
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.
|
bbeo-js-pattern-array-38-findLast
|
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.
|
bbeo-js-pattern-array-39-flatten
|
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.
|
bbeo-js-pattern-array-40-forEachRight
|
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.
|
bbeo-js-pattern-object-41-forOwn
|
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.
|
bbeo-js-pattern-func-42-functionName
|
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.
|
bbeo-js-pattern-date-43-Get Time From Date
|
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.
|
bbeo-js-pattern-date-44-Get Days Between Dates
|
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.
|
bbeo-js-pattern-dom-45-getStyle
|
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.
|
bbeo-js-pattern-test-46-getType
|
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.
|
bbeo-js-pattern-dom-47-hasClass
|
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.
|
bbeo-js-pattern-array-48-head
|
const head = arr => arr[0];
head([1, 2, 3]); // 1
|
[pattern]: This snippet returns the of a list.
|
bbeo-js-pattern-dom-49-hide
|
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.
|
bbeo-js-pattern-bom-50-httpsRedirect
|
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.
|
bbeo-js-pattern-array-51-indexOfAll
|
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.
|
bbeo-js-pattern-array-52-initial
|
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.
|
bbeo-js-pattern-dom-53-insertAfter
|
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.
|
bbeo-js-pattern-dom-54-insertBefore
|
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.
|
bbeo-js-pattern-array-55-intersection
|
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.
|
bbeo-js-pattern-array-56-intersectionBy
|
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.
|
bbeo-js-pattern-array-57-intersectionWith
|
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.
|
bbeo-js-pattern-test-58-is
|
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.
|
bbeo-js-pattern-test-59-isAfterDate
|
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.
|
bbeo-js-pattern-test-60-isAnagram
|
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.
|
bbeo-js-pattern-test-61-isArrayLike
|
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.
|
bbeo-js-pattern-test-62-isBeforeDate
|
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.
|
bbeo-js-pattern-test-63-isBoolean
|
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.
|
bbeo-js-pattern-test-64-isBrowser
|
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).
|
bbeo-js-pattern-test-65-isBrowserTabFocused
|
const isBrowserTabFocused = () => !document.hidden;
isBrowserTabFocused(); // true
|
[pattern]: This snippet can be used to determine whether the browser tab is focused.
|
bbeo-js-pattern-test-66-isLowerCase
|
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.
|
bbeo-js-pattern-test-67-isNil
|
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 .
|
bbeo-js-pattern-test-68-isNull
|
const isNull = val => val === null;
isNull(null); // true
|
[pattern]: This snippet can be used to check whether a value is .
|
bbeo-js-pattern-test-69-isNumber
|
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.
|
bbeo-js-pattern-test-70-isObject
|
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.
|
bbeo-js-pattern-test-71-isObjectLike
|
const isObjectLike = val => val !== null && typeof val === 'object';
isObjectLike({}); // true
isObjectLike([1, 2, 3]); // true
isObjectLike(x => x); // false
isObjectLike(null); // false
|
[pattern]: This snippet can be used to check if a value is not and that its is “object”.
|
bbeo-js-pattern-test-72-isPlainObject
|
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
isPlainObject({ a: 1 }); // true
isPlainObject(new Map()); // false
|
[pattern]: This snippet checks whether a value is an object created by the Object constructor.
|
bbeo-js-pattern-test-73-isPromiseLike
|
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
|
[pattern]: This snippet checks whether an object looks like a .
|
bbeo-js-pattern-test-74-isSameDate
|
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
|
[pattern]: This snippet can be used to check whether two dates are equal.
|
bbeo-js-pattern-test-75-isString
|
const isString = val => typeof val === 'string';
isString('10'); // true
|
[pattern]: This snippet can be used to check whether an argument is a string.
|
bbeo-js-pattern-test-76-isSymbol
|
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
|
[pattern]: This snippet can be used to check whether an argument is a symbol.
|
bbeo-js-pattern-test-77-isUndefined
|
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
|
[pattern]: This snippet can be used to check whether a value is undefined.
|
bbeo-js-pattern-test-78-isUpperCase
|
const isUpperCase = str => str === str.toUpperCase();
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false
|
[pattern]: This snippet can be used to check whether a string is upper case.
|
bbeo-js-pattern-test-79-isValidJSON
|
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
|
[pattern]: This snippet can be used to check whether a string is a valid JSON.
|
bbeo-js-pattern-array-80-last
|
const last = arr => arr[arr.length - 1];
last([1, 2, 3]); // 3
|
[pattern]: This snippet returns the last element of an array.
|
bbeo-js-pattern-object-81-matches
|
const matches = (obj, source) =>
Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
|
[pattern]: This snippet compares two objects to determine if the first one contains the same property values as the second one.
|
bbeo-js-pattern-date-82-maxDate
|
const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));
const array = [
new Date(2017, 4, 13),
new Date(2018, 2, 12),
new Date(2016, 0, 10),
new Date(2016, 0, 9)
];
maxDate(array); // 2018-03-11T22:00:00.000Z
|
[pattern]: This snippet can be used to get the latest date.
|
bbeo-js-pattern-array-83-maxN
|
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2]
|
[pattern]: This snippet returns the largest elements from a list. If is greater than or equal to the list’s length, then it will return the original list (sorted in descending order).
|
bbeo-js-pattern-date-84-minDate
|
const minDate = (...dates) => new Date(Math.min.apply(null, ...dates));
const array = [
new Date(2017, 4, 13),
new Date(2018, 2, 12),
new Date(2016, 0, 10),
new Date(2016, 0, 9)
];
minDate(array); // 2016-01-08T22:00:00.000Z
|
[pattern]: This snippet can be used to get the earliest date.
|
bbeo-js-pattern-array-85-minN
|
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]
|
[pattern]: This snippet returns the smallest elements from a list. If is greater than or equal to the list’s length, then it will return the original list (sorted in ascending order).
|
bbeo-js-pattern-func-86-negate
|
const negate = func => (...args) => !func(...args);
[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
|
[pattern]: This snippet can be used to apply the not operator () to a predicate function with its arguments.
|
bbeo-js-pattern-dom-87-nodeListToArray
|
const nodeListToArray = nodeList => [...nodeList];
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
|
[pattern]: This snippet can be used to convert a to an array.
|
bbeo-js-pattern-string-88-pad
|
const pad = (str, length, char = ' ') =>
str.padStart((str.length + length) / 2, char).padEnd(length, char);
pad('cat', 8); // ' cat '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'
|
[pattern]: This snippet can be used to a string on both sides with a specified character if it is shorter than the specified length.
|
bbeo-js-pattern-cast-89-radsToDegrees
|
const radsToDegrees = rad => (rad * 180.0) / Math.PI;
radsToDegrees(Math.PI / 2); // 90
|
[pattern]: This snippet can be used to convert an angle from radians to degrees.
|
bbeo-js-pattern-gen-90-randomHexColorCode
|
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode(); // "#e34155"
|
[pattern]: This snippet can be used to generate a random hexadecimal color code.
|
bbeo-js-pattern-gen-91-randomIntArrayInRange
|
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
|
[pattern]: This snippet can be used to generate an array with random integers in a specified range.
|
bbeo-js-pattern-gen-92-randomIntegerInRange
|
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5); // 3
|
[pattern]: This snippet can be used to generate a random integer in a specified range.
|
bbeo-js-pattern-gen-93-randomNumberInRange
|
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
randomNumberInRange(2, 10); // 6.0211363285087005
|
[pattern]: This snippet can be used to return a random number in a specified range.
|
bbeo-js-pattern-lib-94-readFileLines
|
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']
|
[pattern]: This snippet can be used to read a file by getting an array of lines from a file.
|
bbeo-js-pattern-bom-95-redirect
|
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://google.com');
|
[pattern]: This snippet can be used to do a redirect to a specified URL.
|
bbeo-js-pattern-string-96-reverse
|
const reverseString = str => [...str].reverse().join('');
reverseString('foobar'); // 'raboof'
|
[pattern]: This snippet can be used to reverse a string.
|
bbeo-js-pattern-math-97-round
|
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01
|
[pattern]: This snippet can be used to round a number to a specified number of digits.
|
bbeo-js-pattern-promise-98-runPromisesInSeries
|
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
// Executes each promise sequentially, taking a total of 3 seconds to complete
|
[pattern]: This snippet can be used to run an array of promises in series.
|
bbeo-js-pattern-array-99-sample
|
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
sample([3, 7, 9, 11]); // 9
|
[pattern]: This snippet can be used to get a random number from an array.
|
bbeo-js-pattern-array-100-sampleSize
|
const sampleSize = ([...arr], n = 1) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr.slice(0, n);
};
sampleSize([1, 2, 3], 2); // [3,1]
sampleSize([1, 2, 3], 4); // [2,3,1]
|
[pattern]: This snippet can be used to get random elements from unique positions from an array up to the size of the array. Elements in the array are shuffled using the .
|
bbeo-js-pattern-dom-101-scrollToTop
|
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
scrollToTop();
|
[pattern]: This snippet can be used to do a smooth scroll to the top of the current page.
|
bbeo-js-pattern-string-102-serializeCookie
|
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
serializeCookie('foo', 'bar'); // 'foo=bar'
|
[pattern]: This snippet can be used to serialize a cookie name-value pair into a Set-Cookie header string.
|
bbeo-js-pattern-dom-103-setStyle
|
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
setStyle(document.querySelector('p'), 'font-size', '20px');
// The first <p> element on the page will have a font-size of 20px
|
[pattern]: This snippet can be used to set the value of a CSS rule for a particular element.
|
bbeo-js-pattern-gen-104-shallowClone
|
const shallowClone = obj => Object.assign({}, obj);
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b
|
[pattern]: This snippet can be used to create a shallow clone of an object.
|
bbeo-js-pattern-dom-105-show
|
const show = (...el) => [...el].forEach(e => (e.style.display = ''));
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page
|
[pattern]: This snippet can be used to show all the elements specified.
|
bbeo-js-pattern-array-106-shuffle
|
const shuffle = ([...arr]) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
};
const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]
|
[pattern]: This snippet can be used to order the elements of an array randomly using the .
|
bbeo-js-pattern-array-107-similarity
|
const similarity = (arr, values) => arr.filter(v => values.includes(v))
similarity([1, 2, 3], [1, 2, 4]); // [1, 2]
|
[pattern]: This snippet can be used to return an array of elements that appear in two arrays.
|
bbeo-js-pattern-promise-108-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.');
}
|
[pattern]: This snippet can be used to delay the execution of an asynchronous function by putting it into sleep.
|
bbeo-js-pattern-dom-130-smoothScroll
|
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar'); // scrolls smoothly to the element with the fooBar id
smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar
|
[pattern]: This snippet can be used to smoothly scroll the element on which it is called into the visible area of the browser window.
|
bbeo-js-pattern-string-110-sortCharactersInString
|
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
sortCharactersInString('cabbage'); // 'aabbceg'
|
[pattern]: This snippet can be used to alphabetically sort the characters in a string.
|
bbeo-js-pattern-cast-111-splitLines
|
const splitLines = str => str.split(/\r?\n/);
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
|
[pattern]: This snippet can be used to split a multi-line string into an array of lines.
|
bbeo-js-pattern-dom-112-stripHTMLTags
|
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
|
[pattern]: This snippet can be used to remove HTML/XML tags from a string.
|
bbeo-js-pattern-array-113-sum
|
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
|
[pattern]: This snippet can be used to find the sum of two or more numbers or arrays.
|
bbeo-js-pattern-array-114-tail
|
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
tail([1, 2, 3]); // [2,3]
tail([1]); // [1]
|
[pattern]: This snippet can be used to get an array with all the elements of an array except for the first one. If the array has only one element, then that an array with that element will be returned instead.
|
bbeo-js-pattern-array-115-take
|
const take = (arr, n = 1) => arr.slice(0, n);
take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3], 0); // []
|
[pattern]: This snippet can be used to get an array with elements removed from the beginning.
|
bbeo-js-pattern-array-116-takeRight
|
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
takeRight([1, 2, 3], 2); // [ 2, 3 ]
takeRight([1, 2, 3]); // [3]
|
[pattern]: This snippet can be used to get an array with elements removed from the end.
|
bbeo-js-pattern-func-117-timeTaken
|
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
|
[pattern]: This snippet can be used to find out the time it takes to execute a function.
|
bbeo-js-pattern-func-118-times
|
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
|
[pattern]: This snippet can be used to iterate over a callback times.
|
bbeo-js-pattern-cast-119-toCurrency
|
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
|
[pattern]: This snippet can be used to format a number like a currency.
|
bbeo-js-pattern-cast-120-toDecimalMark
|
const toDecimalMark = num => num.toLocaleString('en-US');
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
|
[pattern]: This snippet uses the function to convert float-point arithmetic to the decimal mark form by using a number to make a comma-separated string.
|
bbeo-js-pattern-dom-121-toggleClass
|
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
|
[pattern]: This snippet can be used to toggle a class for an element.
|
bbeo-js-pattern-date-122-tomorrow
|
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return t.toISOString().split('T')[0];
};
tomorrow(); // 2019-09-08 (if current date is 2018-09-08)
|
[pattern]: This snippet can be used to get a string representation of tomorrow’s date.
|
bbeo-js-pattern-func-123-unfold
|
const unfold = (fn, seed) => {
let result = [],
val = [null, seed];
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
|
[pattern]: This snippet can be used to build an array using an iterator function and an initial seed value.
|
bbeo-js-pattern-array-124-union
|
const union = (a, b) => Array.from(new Set([...a, ...b]));
union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
|
[pattern]: This snippet can be used to find the of two arrays, resulting in an array that has elements that come from both arrays but that do not repeat.
|
bbeo-js-pattern-array-125-uniqueElements
|
const uniqueElements = arr => [...new Set(arr)];
uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
|
[pattern]: This snippet uses ES6 andtheoperator to get every element only once.
|
bbeo-js-pattern-test-126-validateNumber
|
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
validateNumber('10'); // true
|
[pattern]: This snippet can be used to check whether a value is a number.
|
bbeo-js-pattern-cast-127-words
|
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
|
[pattern]: This snippet converts a string into an array of words.
|
bbeo-js-pattern-gen-128-getES6moduleSyntaxBySource
|
export function getES6moduleSyntaxBySource(source, extension) {
const fixVarName = varName => varName.replace(/-/g, '_');
const dropRight = (arr, n = 1) => arr.slice(0, -n);
let sourceList = fsReadDir(source);
let sourceES6 = [];
sourceList.forEach(source => {
if (source.endsWith(extension)) {
sourceES6.push(dropRight(source, 3));
}
});
return sourceES6.map(
source => `import { ${fixVarName(source)} } from './${source}.js';`,
);
}
|
[pattern]: Get all ES6 modules syntax from the source directory
|
bbeo-js-pattern-gen-129-concatJSONsourcesToOneFile
|
export function concatJSONsourcesToOneFile(sourcesList, distPath) {
const refactorSourceList = sourceList => {
let objRefactored = {};
sourceList.forEach(source => {
objRefactored = { ...objRefactored, ...source };
});
return objRefactored;
};
const JSONexportation = (sourceList, distPath) => {
fs.writeFileSync(distPath, JSON.stringify(sourceList), 'utf8', err => {
console.log(err ? err : 'The file was saved!');
});
};
JSONexportation(refactorSourceList(sourcesList), distPath);
}
|
[pattern]: Concat & export all external JSON sources to one JSON file
|
bbeo-js-pattern-test-131-validateEmail
|
const validateEmail = email => {
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(email);
};
|
[pattern]: Email validator with regex
|