π 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
- [x] Javascript snippets collection
- [x] Javascript patterns collection
- [x] Some snippets on frequently used javascript libraries
- [ ] Typescript snippets collection
- [ ] Typescript patterns collection
- [x] React snippets collection (beta)
- [x] React patterns collection (beta)
- [ ] Python snippets collection
- [ ] Python patterns collection
- [ ] Shell script snippets collection
- [ ] Shell script patterns collection
- [x] CSS patterns collection (beta)
π Contribution
install all dependencies
needed to work in this project by running the following command (in root directory):
npm install
snippets
& patterns
file and regenerate the documentation, all in one command (in root directory):
npm run build
grunt task
to make a local backup
of this project by running the following command (in root directory):
npm run backups
π Stats
βΎ Total stats
Languages | Patterns | Libraries | Snippets |
---|---|---|---|
JavaScript | 131 |
2 |
20 |
Python | 0 |
0 |
0 |
React | 18 |
- |
3 |
Shell Script | 0 |
- |
0 |
TypeScript | 0 |
- |
0 |
CSS | 2 |
- |
- |
βΎ List stats
Languages | Patterns | Libraries | Snippets |
---|---|---|---|
JavaScript | array-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-validateEmail
|
fs traverse
|
array 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 |
React | gen-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 |
CSS | treeviewCSS toolTipCSS
|
- |
- |
βΎ Patterns triggers categories
Languages | Patterns |
---|---|
JavaScript | array - object - func - test (regex) - math - dom - bom - date - cast - mixte - hybrid - string - gen (tools) - lib - promise |
Python | - |
React | gen - state - jsx - comp (component) |
Shell Script | - |
TypeScript | - |
CSS | - |
π Usage
Snippets & Patterns Index |
---|
Notation: hybrid = string | array -- mixte = array | object
βΎ Javascript snippets
prefix | body | description |
---|---|---|
bbeo-js-array-ascElement |
${1:array_var}.sort((${2:a},${3:b}) => ${2:a} - ${3:b}) |
|
bbeo-js-array-descElement |
${1:array_var}.sort((${2:a},${3:b}) => ${3:b} - ${2:a}) |
|
bbeo-js-array-slice |
${1:array_var}.slice(${2:start}, ${3:end+1}) |
|
bbeo-js-array-join |
${1:array_var}.join(${2:delimiter}) |
|
bbeo-js-array-flat |
${1:array_var}.flat(${2:depth}) |
|
bbeo-js-array-isEmpty |
${1:array_var}.length === 0 ? true : false |
|
bbeo-array-js-removeDuplicates |
[...new Set(${1:array_var})] |
|
bbeo-js-array-reverse |
${1:array_var}.reverse() |
|
bbeo-js-basic-ifCondition |
if (${1:condition}) {
${3:condition_body}
} else if (${2:condition}) {
${4:condition_body}
} else {
${5:condition_body}
} |
|
bbeo-js-basic-forLoop |
for (let ${1:index} = 0; ${1:index} < ${2:array_length}; ${1:index}++) {
${3:for_body}
} |
|
bbeo-js-basic-whileLoop |
while (${1:condition}) {
${2:while_body}
} |
|
bbeo-js-basic-doWhileLoop |
do {
${2:do_body}
} while (${1:condition}); |
|
bbeo-js-basic-forInLoop |
for (let ${1:e} in ${2:array_var}) {
${3:for_body}
} |
|
bbeo-js-basic-forOfLoop |
for (let ${1:e} of ${2:array_var}) {
${3:for_body}
} |
|
bbeo-js-basic-forEachLoop |
${2:array_var}.forEach((${1:e}) => {
${3:for_body}
}); |
|
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;
} |
|
bbeo-js-basic-tryCatchStatement |
try {
${1:try_body}
} catch (${2:error}) {
${3:catch_body}
} |
|
bbeo-js-basic-tryCatchFinallyStatement |
try {
${1:try_body}
} catch (${2:error}) {
${3:catch_body}
} finally {
${4:finally_body}
} |
|
bbeo-js-basic-tryCatchFinallyStatementMultiple |
try {
${1:try_body}
} catch (${2:error}) {
${3:catch_body}
} catch (${4:error}) {
${5:catch_body}
} finally {
${6:finally_body}
} |
|
bbeo-js-bom-addWindowEventListener |
window.addEventListener(${1:'resize, scroll'}, ${2:callback}) |
|
bbeo-js-cast-objToString1 |
${1:object}.toString() |
|
bbeo-js-cast-objToString2 |
String(${1:object}) |
|
bbeo-js-cast-stringToArray1 |
Array.from(${1:string_var}) |
|
bbeo-js-cast-stringToArray2 |
[... ${1:string_var}] |
|
bbeo-js-cast-stringToArray3 |
${1:string_var}.split`` |
|
bbeo-js-cast-stringToNumber1 |
Number(${1:string_var}) |
|
bbeo-js-cast-stringToNumber2 |
parseInt(${1:string_var}) |
|
bbeo-js-cast-hex2dec |
+('0x'+ ${1:hex_var}) |
|
bbeo-js-cast-dec2hex |
${1:dec_var}.toString(16) |
|
bbeo-js-cast-oct2dec |
parseInt(${1:oct_var}, 8) |
|
bbeo-js-cast-dec2oct |
${1:dec_var}.toString(8) |
|
bbeo-js-cast-bin2dec |
parseInt(${bin_var}, 2) |
|
bbeo-js-cast-dec2bin |
${1:dec_var}.toString(2) |
|
bbeo-js-class-getter |
get ${1:property_name} () { return this.${1:property_name}; } |
|
bbeo-js-class-setter |
set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; } |
|
bbeo-js-class-method |
${1:method_name} () { ${2:method_body} } |
|
bbeo-js-class-constructor |
constructor () { ${1:constructor_body} } |
|
bbeo-js-class-staticMethod |
static ${1:method_name} () { ${2:method_body} } |
|
bbeo-js-class-staticProperty |
static ${1:property_name} = ${2:property_value} |
|
bbeo-js-class-staticGetter |
static get ${1:property_name} () { return this.${1:property_name}; } |
|
bbeo-js-class-staticSetter |
static set ${1:property_name} (${2:value}) { this.${1:property_name} = ${2:value}; } |
|
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)
}
} |
|
bbeo-js-console-clg |
console.log(${1:object}) |
|
bbeo-js-console-clr |
console.error(${1:object}) |
|
bbeo-js-console-clt |
console.table(${1:object}) |
|
bbeo-js-console-cli |
console.info(${1:object}) |
|
bbeo-js-console-clw |
console.warn(${1:object}) |
|
bbeo-js-date-createNullDate |
const ${1:date_objVar} = new Date() |
|
bbeo-js-date-createFullDate |
const ${1:date_objVar} = new Date(${2:year}, ${3:month}, ${4:day}, ${5:hour}, ${6:minute}, ${7:second}, ${8:millisecond}) |
|
bbeo-js-date-createStringDate |
const ${1:date_objVar} = new Date(${2:date_string}) |
|
bbeo-js-date-now |
${1:date_objVar}.now() |
|
bbeo-js-date-day |
${1:date_objVar}.getDay() |
|
bbeo-js-date-month |
${1:date_objVar}.getMonth() |
|
bbeo-js-date-year |
${1:date_objVar}.getFullYear() |
|
bbeo-js-date-hour |
${1:date_objVar}.getHours() |
|
bbeo-js-date-minute |
${1:date_objVar}.getMinutes() |
|
bbeo-js-date-second |
${1:date_objVar}.getSeconds() |
|
bbeo-js-date-millisecond |
${1:date_objVar}.getMilliseconds() |
|
bbeo-js-date-time |
${1:date_objVar}.getTime() |
|
bbeo-js-date-toString |
${1:date_objVar}.toString() |
|
bbeo-js-date-setDate |
${1:date_objVar}.setDate(${2:new_date}) |
|
bbeo-js-date-setMonth |
${1:date_objVar}.setMonth(${2:new_month}) |
|
bbeo-js-date-setYear |
${1:date_objVar}.setFullYear(${2:new_year}) |
|
bbeo-js-date-setHour |
${1:date_objVar}.setHours(${2:new_hour}) |
|
bbeo-js-date-setMinute |
${1:date_objVar}.setMinutes(${2:new_minute}) |
|
bbeo-js-date-setSecond |
${1:date_objVar}.setSeconds(${2:new_second}) |
|
bbeo-js-date-setMillisecond |
${1:date_objVar}.setMilliseconds(${2:new_millisecond}) |
|
bbeo-js-date-setTime |
${1:date_objVar}.setTime(${2:new_time}) |
|
bbeo-js-destruct-assignArray |
const [${1:var1}, ${2:var2}] = [${3:value1}, ${4:value2}] |
|
bbeo-js-destruct-assignObject |
const {${1:attrib1}, ${2:attrib2}} = ${3:object_container} |
|
bbeo-js-dom-id |
document.getElementById(${1:id}) |
|
bbeo-js-dom-class |
document.getElementsByClassName(${1:class}) |
|
bbeo-js-dom-tag |
document.getElementsByTagName(${1:tag}) |
|
bbeo-js-dom-query |
document.querySelector(${1:query}) |
|
bbeo-js-dom-queryAll |
document.querySelectorAll(${1:query}) |
|
bbeo-js-dom-name |
document.getElementsByName(${1:name}) |
|
bbeo-js-dom-createHTMLElement |
document.createElement(${1:tag}) |
|
bbeo-js-dom-createTextNode |
document.createTextNode(${1:text}) |
|
bbeo-js-dom-id-innerHTML |
document.getElementById(${1:id}).innerHTML = ${2:html} |
|
bbeo-js-dom-id-textContent |
document.getElementById(${1:id}).textContent = ${2:text} |
|
bbeo-js-dom-id-value |
document.getElementById(${1:id}).value = ${2:value} |
|
bbeo-js-dom-id-attribute |
document.getElementById(${1:id}).setAttribute(${2:attribute}, ${3:value}) |
|
bbeo-js-dom-id-getAttribute |
document.getElementById(${1:id}).getAttribute(${2:attribute}) |
|
bbeo-js-dom-id-removeAttribute |
document.getElementById(${1:id}).removeAttribute(${2:attribute}) |
|
bbeo-js-dom-id-addClass |
document.getElementById(${1:id}).classList.add(${2:class}) |
|
bbeo-js-dom-id-removeClass |
document.getElementById(${1:id}).classList.remove(${2:class}) |
|
bbeo-js-dom-id-toggleClass |
document.getElementById(${1:id}).classList.toggle(${2:class}) |
|
bbeo-js-dom-id-hasClass |
document.getElementById(${1:id}).classList.contains(${2:class}) |
|
bbeo-js-dom-id-appendChild |
document.getElementById(${1:id}).appendChild(${2:child}) |
|
bbeo-js-dom-id-removeChild |
document.getElementById(${1:id}).removeChild(${2:child}) |
|
bbeo-js-dom-id-insertBefore |
document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference}) |
|
bbeo-js-dom-id-insertAfter |
document.getElementById(${1:id}).insertBefore(${2:child}, ${3:reference}.nextSibling) |
|
bbeo-js-dom-id-replaceChild |
document.getElementById(${1:id}).replaceChild(${2:child}, ${3:reference}) |
|
bbeo-js-dom-id-childNodes |
document.getElementById(${1:id}).childNodes |
|
bbeo-js-dom-id-firstChild |
document.getElementById(${1:id}).firstChild |
|
bbeo-js-dom-id-lastChild |
document.getElementById(${1:id}).lastChild |
|
bbeo-js-dom-id-parentNode |
document.getElementById(${1:id}).parentNode |
|
bbeo-js-dom-id-addEventListener |
document.getElementById(${1:id}).addEventListener(${2:click, 'keypress, scroll, mouseenter, mouseout, input, submit, load'}, ${3:callback}) |
|
bbeo-js-dom-eventTargetValue |
${1:e}.target.value |
|
bbeo-js-dom-id-addEventListenerWithpreventDefault |
document.getElementById(${1:id}).addEventListener(${2:'submit'}, ${3:e} => {
${3:e}.preventDefault()
}) |
|
bbeo-js-dom-id-addEventListenerWithstopPropagation |
document.getElementById(${1:id}).addEventListener(${2:click, 'keypress, scroll, mouseenter, mouseout, input, submit, load'}, ${3:e} => {
${3:e}.stopPropagation()
}) |
|
bbeo-js-func-arrowFunc |
const ${1:func_name} = (${2:args}) => {
${3:code...}
} |
|
bbeo-js-gen-permut |
[${1:a},${2:b}] = [${2:b},${1:a}] |
|
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 |
|
bbeo-js-gen-alphaGen |
String.fromCharCode(...Array(123).keys()).slice(97) |
|
bbeo-js-gen-numGen |
[...Array(${1:min(0)~max(n+1)})].map((_, i) => i); |
|
bbeo-js-hybrid-indexOfElement |
${1:hybr_var}.indexOf(${2:e}) |
|
bbeo-js-hybrid-includesElement |
${1:hybr_var}.includes(${2:e}) |
|
bbeo-js-hybrid-length |
${1:hybr_var}.length |
|
bbeo-js-math-dot |
${1:number_var}.toFixed(${2:decal}) |
|
bbeo-js-math-pow |
${1:number_var} ** ${2:exp} |
|
bbeo-js-math-max |
Math.max(... ${1: element}) |
|
bbeo-js-math-min |
Math.min(... ${1: element}) |
|
bbeo-js-math-expOfNumber |
Math.log(${solution})/Math.log(${base}) |
|
bbeo-js-math-sqrt |
Math.sqrt(${1:number}) |
|
bbeo-js-math-abs |
Math.abs(${1:number}) |
|
bbeo-js-math-round |
Math.round(${1:number}) |
|
bbeo-js-math-ceil |
Math.ceil(${1:number}) |
|
bbeo-js-math-floor |
Math.floor(${1:number}) |
|
bbeo-js-math-random |
Math.random() |
|
bbeo-js-math-random-max |
Math.floor(Math.random() * ${1:max}) |
|
bbeo-js-math-random-minMax |
Math.floor(Math.random() * (${1:max} - ${2:min}) + ${2:min}) |
|
bbeo-js-math-pi |
Math.PI |
|
bbeo-js-math-e |
Math.E |
|
bbeo-js-math-ln2 |
Math.LN2 |
|
bbeo-js-math-ln10 |
Math.LN10 |
|
bbeo-js-mixte-findElement |
${1:mixte_var}.find(${2:e} => ${2:e} ${3:===} ${4:foo}) |
|
bbeo-js-mixte-someElement |
${1:mixte_var}.some(${2:e} => ${2:e} ${3:===} ${4:foo}) |
|
bbeo-js-mixte-everyElement |
${1:mixte_var}.every(${2:e} => ${2:e} ${3:===} ${4:foo}) |
|
bbeo-js-mixte-mapElement |
${1:mixte_var}.map(${2:e} => {${3:expression}}) |
|
bbeo-js-mixte-filterElement |
${1:mixte_var}.filter(${2:e} => {${3:condition}}) |
|
bbeo-js-mixte-reduceElement |
${1:mixte_var}.reduce((${2:total, e}) => {${3:total + e}}) |
|
bbeo-js-mixte-fillElement |
${1:mixte_var}.fill(${2:start_index},${3:foo}) |
|
bbeo-js-mixte-foreachElement |
${1:mixte_var}.forEach((${2:e}) => {
${3:expression}
}) |
|
bbeo-js-module-imp |
import ${1:module_name} from ${2:module_source}; |
|
bbeo-js-module-imd |
import { ${1:module_name} } from ${2:module_source}; |
|
bbeo-js-object-extractValues |
Object.values(${1:object_var}) |
|
bbeo-js-object-extractEntries |
Object.entries(${1:object_var}) |
|
bbeo-js-object-length |
Object.keys(${1:object_var}).length |
|
bbeo-js-regex-numExtract |
${1:string_var}.match(/\d/g); |
|
bbeo-js-regex-occTotal |
const ${1:string_var} = ${2:string_value}
${3:occ_name}=(${1:string_var}.match(/${4:arg}/g)||[]).length |
|
bbeo-js-regex-ifExist |
${1:string_var}.match(/${2:arg}/) |
|
bbeo-js-regex-startOf |
${1:string_var}.match(/^${2:arg}/) |
|
bbeo-js-regex-endOf |
${1:string_var}.match(/^${2:arg}/) |
|
bbeo-js-regex-ifExistOR |
${1:string_var}.match(/${2:a}|${3:b}/) |
|
bbeo-spread-mergeArrays |
[...${1:arr1}, ...${2:arr2}] |
|
bbeo-spread-mergeObjects |
{...${1:obj1}, ...${2:obj2}} |
|
bbeo-spread-removeDuplicates |
[...new Set(${1:array_var})] |
|
bbeo-spread-addProp |
{...${1:obj_var}, ${2:newProp}: ${3:foo}} |
|
bbeo-js-string-replace |
${1:string_var}.replace(${2:'input'}, ${3:'output'}) |
|
bbeo-js-string-replaceAll |
${1:string_var}.replaceAll(${2:'input'}, ${3:'output'}) |
|
bbeo-js-string-split |
${1:string_var}.split(${2:'delimiter'}) |
|
bbeo-js-string-sub |
${1:string_var}.substr(${2:start}, ${3:end+1}) |
|
bbeo-js-string-repeat |
${1:string_var}.repeat(${2:N}) |
|
bbeo-js-string-trim |
${1:string_var}.trim() |
|
bbeo-js-string-charAt |
${1:string_var}.charAt(${2:index}) |
|
bbeo-js-string-startsWith |
${1:string_var}.startsWith(${2:input}, ${3:start_index}) |
|
bbeo-js-string-endsWith |
${1:string_var}.endsWith(${2:input}, ${3:end_index}) |
|
bbeo-js-string-toLowerCase |
${1:string_var}.toLowerCase() |
|
bbeo-js-string-toUpperCase |
${1:string_var}.toUpperCase() |
|
bbeo-js-struct-addToQueue |
${1:array_var}.push(${2:e}) |
|
bbeo-js-struct-addToHead |
${1:array_var}.unshift(${2:e}) |
|
bbeo-js-struct-deleteAtTail |
${1:array_var}.pop(${2:e}) |
|
bbeo-js-struct-deleteAtHead |
${1:array_var}.shift(${2:e}) |
|
βΎ Javascript patterns
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 |
|
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 |
|
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 |
|
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"'``` |
|
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'); |
|
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 = [] |
|
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 |
|
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 |
|
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'] ] |
|
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'] ] |
|
bbeo-js-pattern-dom-11-bottomVisible |
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true |
|
bbeo-js-pattern-cast-12-byteSize |
const byteSize = str => new Blob([str]).size;
byteSize('π'); // 4
byteSize('Hello World'); // 11 |
|
bbeo-js-pattern-string-13-capitalize |
const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join('');
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar' |
|
bbeo-js-pattern-string-14-capitalizeEveryWord |
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!' |
|
bbeo-js-pattern-cast-15-castArray |
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1] |
|
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 ] |
|
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 |
|
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 |
|
bbeo-js-pattern-bom-19-currentURL |
const currentURL = () => window.location.href;
currentURL(); // 'https://medium.com/@fatosmorina' |
|
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 |
|
bbeo-js-pattern-string-21-decapitalize |
const decapitalize = ([first, ...rest]) =>
first.toLowerCase() + rest.join('')
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar' |
|
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] |
|
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 } |
|
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' |
|
bbeo-js-pattern-cast-25-degreesToRads |
const degreesToRads = deg => (deg * Math.PI) / 180.0;
degreesToRads(90.0); // ~1.5708 |
|
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] |
|
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 } ] |
|
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] |
|
bbeo-js-pattern-cast-29-digitize |
const digitize = n => [...`${n}`].map(i => parseInt(i));
digitize(431); // [4, 3, 1] |
|
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 |
|
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); // [] |
|
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); // [] |
|
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] |
|
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] |
|
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 |
|
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] |
|
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' |
|
bbeo-js-pattern-array-38-findLast |
const findLast = (arr, fn) => arr.filter(fn).pop();
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 |
|
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] |
|
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' |
|
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 |
|
bbeo-js-pattern-func-42-functionName |
const functionName = fn => (console.debug(fn.name), fn);
functionName(Math.max); // max (logged in debug channel of console) |
|
bbeo-js-pattern-date-43-Get Time From Date |
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // "08:38:00" |
|
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 |
|
bbeo-js-pattern-dom-45-getStyle |
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
getStyle(document.querySelector('p'), 'font-size'); // '16px' |
|
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' |
|
bbeo-js-pattern-dom-47-hasClass |
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true |
|
bbeo-js-pattern-array-48-head |
const head = arr => arr[0];
head([1, 2, 3]); // 1 |
|
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 |
|
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 |
|
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); // [] |
|
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] |
|
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> |
|
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> |
|
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] |
|
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] |
|
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] |
|
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 |
|
bbeo-js-pattern-test-59-isAfterDate |
const isAfterDate = (dateA, dateB) => dateA > dateB;
isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true |
|
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 |
|
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 |
|
bbeo-js-pattern-test-62-isBeforeDate |
const isBeforeDate = (dateA, dateB) => dateA < dateB;
isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true |
|
bbeo-js-pattern-test-63-isBoolean |
const isBoolean = val => typeof val === 'boolean';
isBoolean(null); // false
isBoolean(false); // true |
|
bbeo-js-pattern-test-64-isBrowser |
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
isBrowser(); // true (browser)
isBrowser(); // false (Node) |
|
bbeo-js-pattern-test-65-isBrowserTabFocused |
const isBrowserTabFocused = () => !document.hidden;
isBrowserTabFocused(); // true |
|
bbeo-js-pattern-test-66-isLowerCase |
const isLowerCase = str => str === str.toLowerCase();
isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false |
|
bbeo-js-pattern-test-67-isNil |
const isNil = val => val === undefined || val === null;
isNil(null); // true
isNil(undefined); // true |
|
bbeo-js-pattern-test-68-isNull |
const isNull = val => val === null;
isNull(null); // true |
|
bbeo-js-pattern-test-69-isNumber |
const isNumber = val => typeof val === 'number';
isNumber('1'); // false
isNumber(1); // true |
|
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 |
|
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 |
|
bbeo-js-pattern-test-72-isPlainObject |
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
isPlainObject({ a: 1 }); // true
isPlainObject(new Map()); // false |
|
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 |
|
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 |
|
bbeo-js-pattern-test-75-isString |
const isString = val => typeof val === 'string';
isString('10'); // true |
|
bbeo-js-pattern-test-76-isSymbol |
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true |
|
bbeo-js-pattern-test-77-isUndefined |
const isUndefined = val => val === undefined;
isUndefined(undefined); // true |
|
bbeo-js-pattern-test-78-isUpperCase |
const isUpperCase = str => str === str.toUpperCase();
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false |
|
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 |
|
bbeo-js-pattern-array-80-last |
const last = arr => arr[arr.length - 1];
last([1, 2, 3]); // 3 |
|
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 |
|
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 |
|
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] |
|
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 |
|
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] |
|
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 ] |
|
bbeo-js-pattern-dom-87-nodeListToArray |
const nodeListToArray = nodeList => [...nodeList];
nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ] |
|
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' |
|
bbeo-js-pattern-cast-89-radsToDegrees |
const radsToDegrees = rad => (rad * 180.0) / Math.PI;
radsToDegrees(Math.PI / 2); // 90 |
|
bbeo-js-pattern-gen-90-randomHexColorCode |
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode(); // "#e34155" |
|
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 ] |
|
bbeo-js-pattern-gen-92-randomIntegerInRange |
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5); // 3 |
|
bbeo-js-pattern-gen-93-randomNumberInRange |
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
randomNumberInRange(2, 10); // 6.0211363285087005 |
|
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'] |
|
bbeo-js-pattern-bom-95-redirect |
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://google.com'); |
|
bbeo-js-pattern-string-96-reverse |
const reverseString = str => [...str].reverse().join('');
reverseString('foobar'); // 'raboof' |
|
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 |
|
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 |
|
bbeo-js-pattern-array-99-sample |
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
sample([3, 7, 9, 11]); // 9 |
|
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] |
|
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(); |
|
bbeo-js-pattern-string-102-serializeCookie |
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
serializeCookie('foo', 'bar'); // 'foo=bar' |
|
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 |
|
bbeo-js-pattern-gen-104-shallowClone |
const shallowClone = obj => Object.assign({}, obj);
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b |
|
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 |
|
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] |
|
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] |
|
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.');
} |
|
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 |
|
bbeo-js-pattern-string-110-sortCharactersInString |
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
sortCharactersInString('cabbage'); // 'aabbceg' |
|
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.' , ''] |
|
bbeo-js-pattern-dom-112-stripHTMLTags |
const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum' |
|
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 |
|
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] |
|
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); // [] |
|
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] |
|
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 |
|
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 |
|
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 |
|
bbeo-js-pattern-cast-120-toDecimalMark |
const toDecimalMark = num => num.toLocaleString('en-US');
toDecimalMark(12305030388.9087); // "12,305,030,388.909" |
|
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 |
|
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) |
|
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] |
|
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] |
|
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] |
|
bbeo-js-pattern-test-126-validateNumber |
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
validateNumber('10'); // true |
|
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"] |
|
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';`,
);
} |
|
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);
} |
|
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);
}; |
|
βΎ Javascript libraries
prefix | body | description |
---|---|---|
bbeo-js-libs-fs-deps |
import fs from 'fs'; |
|
bbeo-js-libs-fs-fsImport |
export function fsImport(filepath) {
return JSON.parse(
fs.readFileSync(filepath, 'utf8'),
);
}
|
|
bbeo-js-libs-fs-fsExport |
export function fsExport(data, filepath) {
fs.writeFile(filepath, JSON.stringify(data), err => {
if (err) {
console.log(err);
}
});
} |
|
bbeo-js-libs-fs-fsReadDir |
export function fsReadDir(path) {
if (!fs.existsSync(path)){
fs.mkdirSync(path, { recursive: true });
}
return fs.readdirSync(path);
} |
|
bbeo-js-libs-traverse-deps |
import traverse from 'traverse'; |
|
bbeo-js-libs-traverse-props |
// this.node -> The present node on the recursive walk
// this.path -> An array of string keys from the root to the present node
// this.parent -> The context of the node's parent. This is undefined for the root node.
// this.key -> The name of the key of the present node in its parent. This is undefined for the root node. |
|
bbeo-js-libs-traverse-leaves |
var obj = {
a : [1,2,3],
b : 4,
c : [5,6],
d : { e : [7,8], f : 9 },
};
var leaves = traverse(obj).reduce(function (acc, x) {
if (this.isLeaf) acc.push(x);
return acc;
}, []);
console.dir(leaves); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |
|
bbeo-js-libs-traverse-traverseKeyValueByObject |
export function traverseKeyValueByObject(source, key) {
let traverseResult = [];
traverse(source).forEach(function (e) {
if (this.key == key) {
traverseResult.push(e);
}
});
return traverseResult;
} |
|
bbeo-js-libs-traverse-traverseKeyValueByJSON |
export function traverseKeyValueByJSON(source, key) {
let traverseResult = [];
traverse(JSON.parse(fs.readFileSync(source, 'utf8'))).forEach(function (e) {
if (this.key == key) {
traverseResult.push(e);
}
});
return traverseResult;
} |
|
βΎ React snippets
prefix | body | description |
---|---|---|
bbeo-react-gen-classComponent |
export default class ${1:component_name} extends React.Component {
render() {
return (
// code JSX ...
);
}
} |
|
bbeo-react-gen-functionComponent |
export default function ${1:component_name}(${2{...props | ...children}}) {
return
(
// code JSX ...
)
} |
|
bbeo-react-module-react |
import React from 'react'; |
|
bbeo-react-version-18 |
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />); |
|
bbeo-react-version-17 |
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />
document.getElementById('root'),
); |
|
βΎ React patterns
prefix | body | description |
---|---|---|
bbeo-react-pattern-gen-1-useId |
import { useId } from 'react';
export default function App() {
const Users = [
{
id: useId(),
name: 'Rakoto',
},
{
id: useId(),
name: 'Rasoa',
},
];
return (
<div className="app">
{Users.map(user => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
} |
|
bbeo-react-pattern-state-2-setState |
const myComponent = () => {
const [object, setObject] = useState({
name: 'MacGuffin',
click: 0,
});
const handleClick = () => {
setObject({ ...object, click: object.click + 1 });
};
return <div onClick={handleClick}>{object.click}</div>;
}; |
|
bbeo-react-pattern-jsx-4-confitionals2 |
const sampleComponent = () => {
return (
<div>
{
do => {
if (flag && flag2 && !flag3) {
if (flag4) {
<p>Blah</p>
} else if (flag5) {
<p>Meh</p>
} else {
<p>Herp</p>
}
} else {
<p>Derp</p>
}
}
}
</div>
)
}; |
|
bbeo-react-pattern-comp-5-dataList |
function DataList({ isOrdered, data }) {
const list = data.map((val, i) => (
<li key={`${i}_${val}`}>{val}</li>
));
return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>;
}
const names = ['John', 'Paul', 'Mary'];
ReactDOM.render(<DataList data={names}/>, document.getElementById('root'));
ReactDOM.render(<DataList data={names} isOrdered/>, document.getElementById('root')); |
|
bbeo-react-pattern-comp-6-limitedWordTextarea |
function LimitedWordTextarea({ rows, cols, value, limit }) {
const [content, setContent] = React.useState(value);
const [wordCount, setWordCount] = React.useState(0);
const setFormattedContent = text => {
let words = text.split(' ');
if (words.filter(Boolean).length > limit) {
setContent(
text
.split(' ')
.slice(0, limit)
.join(' ')
);
setWordCount(limit);
} else {
setContent(text);
setWordCount(words.filter(Boolean).length);
}
};
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{wordCount}/{limit}
</p>
</div>
);
}
ReactDOM.render(
<LimitedWordTextArea limit={5} value="Hello there!" />,
document.getElementById('root')
); |
|
bbeo-react-pattern-comp-7-accordionItem |
function AccordionItem(props) {
const style = {
collapsed: {
display: 'none'
},
expanded: {
display: 'block'
},
buttonStyle: {
display: 'block',
width: '100%'
}
};
return (
<div>
<button style={style.buttonStyle} onClick={() => props.handleClick()}>
{props.label}
</button>
<div
className="collapse-content"
style={props.isCollapsed ? style.collapsed : style.expanded}
aria-expanded={props.isCollapsed}
>
{props.children}
</div>
</div>
);
}
function Accordion(props) {
const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);
const changeItem = itemIndex => {
if (typeof props.onItemClick === 'function') props.onItemClick(itemIndex);
if (itemIndex !== bindIndex) setBindIndex(itemIndex);
};
const items = props.children.filter(item => item.type.name === 'AccordionItem');
return (
<div className="wrapper">
{items.map(({ props }) => (
<AccordionItem
isCollapsed={bindIndex === props.index}
label={props.label}
handleClick={() => changeItem(props.index)}
children={props.children}
/>
))}
</div>
);
}
ReactDOM.render(
<Accordion defaultIndex="1" onItemClick={console.log}>
<AccordionItem label="A" index="1">
Lorem ipsum
</AccordionItem>
<AccordionItem label="B" index="2">
Dolor sit amet
</AccordionItem>
</Accordion>,
document.getElementById('root')
); |
|
bbeo-react-pattern-comp-8-carousel |
function Carousel(props) {
const [active, setActive] = React.useState(0);
let scrollInterval = null;
const style = {
carousel: {
position: "relative"
},
carouselItem: {
position: "absolute",
visibility: "hidden"
},
visible: {
visibility: "visible"
}
};
React.useEffect(() => {
scrollInterval = setTimeout(() => {
const { carouselItems } = props;
setActive((active + 1) % carouselItems.length);
}, 2000);
});
const { carouselItems, ...rest } = props;
return (
<div style={style.carousel}>
{carouselItems.map((item, index) => {
const activeStyle = active === index ? style.visible : {};
return React.cloneElement(item, {
...rest,
style: {
...style.carouselItem,
...activeStyle
}
});
})}
</div>
);
}
ReactDOM.render(
<Carousel
carouselItems={[
<div>carousel item 1</div>,
<div>carousel item 2</div>,
<div>carousel item 3</div>
]}
/>,
document.getElementById("root")
); |
|
bbeo-react-pattern-comp-9-collapse |
function Collapse(props) {
const [isCollapsed, setIsCollapsed] = React.useState(props.collapsed);
const style = {
collapsed: {
display: "none"
},
expanded: {
display: "block"
},
buttonStyle: {
display: "block",
width: "100%"
}
};
return (
<div>
<button
style={style.buttonStyle}
onClick={() => setIsCollapsed(!isCollapsed)}
>
{isCollapsed ? "Show" : "Hide"} content
</button>
<div
className="collapse-content"
style={isCollapsed ? style.collapsed : style.expanded}
aria-expanded={isCollapsed}
>
{props.children}
</div>
</div>
);
}
ReactDOM.render(
<Collapse>
<h1>This is a collapse</h1>
<p>Hello world!</p>
</Collapse>,
document.getElementById('root')
); |
|
bbeo-react-pattern-comp-10-treeView |
function TreeView({
data,
toggled = true,
name = null,
isLast = true,
isChildElement = false,
isParentToggled = true
}) {
const [isToggled, setIsToggled] = React.useState(toggled);
return (
<div
style={{ marginLeft: isChildElement ? 16 : 4 + "px" }}
className={isParentToggled ? "tree-element" : "tree-element collapsed"}
>
<span
className={isToggled ? "toggler" : "toggler closed"}
onClick={() => setIsToggled(!isToggled)}
/>
{name ? <strong> {name}: </strong> : <span> </span>}
{Array.isArray(data) ? "[" : "{"}
{!isToggled && "..."}
{Object.keys(data).map(
(v, i, a) =>
typeof data[v] == "object" ? (
<TreeView
data={data[v]}
isLast={i === a.length - 1}
name={Array.isArray(data) ? null : v}
isChildElement
isParentToggled={isParentToggled && isToggled}
/>
) : (
<p
style={{ marginLeft: 16 + "px" }}
className={isToggled ? "tree-element" : "tree-element collapsed"}
>
{Array.isArray(data) ? "" : <strong>{v}: </strong>}
{data[v]}
{i === a.length - 1 ? "" : ","}
</p>
)
)}
{Array.isArray(data) ? "]" : "}"}
{!isLast ? "," : ""}
</div>
);
}
let data = {
lorem: {
ipsum: "dolor sit",
amet: {
consectetur: "adipiscing",
elit: [
"duis",
"vitae",
{
semper: "orci"
},
{
est: "sed ornare"
},
"etiam",
["laoreet", "tincidunt"],
["vestibulum", "ante"]
]
},
ipsum: "primis"
}
};
ReactDOM.render(<TreeView data={data} name='data'/>, document.getElementById("root")); |
|
bbeo-react-pattern-comp-11-mailTo |
function Mailto({ email, subject, body, ...props }) {
return (
<a href={`mailto:${email}?subject=${subject || ""}&body=${body || ""}`}>
{props.children}
</a>
);
}
ReactDOM.render(
<Mailto email="foo@bar.baz" subject="Hello" body="Hello world!">
Mail me!
</Mailto>,
document.getElementById("root")
); |
|
bbeo-react-pattern-comp-12-toolTip |
function Tooltip({ children, text, ...rest }) {
const [show, setShow] = React.useState(false);
return (
<div>
<div className="tooltip" style={show ? { visibility: "visible" } : {}}>
{text}
<span className="tooltip-arrow" />
</div>
<div
{...rest}
onMouseEnter={() => setShow(true)}
onMouseLeave={() => setShow(false)}
>
{children}
</div>
</div>
);
} |
|
bbeo-css-pattern-comp-13-ticker |
function Ticker(props) {
const [ticker, setTicker] = React.useState(0);
let interval = null;
const tick = () => {
reset();
interval = setInterval(() => {
if (ticker < props.times)
setTicker(ticker + 1);
else
clearInterval(interval);
}, props.interval);
}
const reset = () => {
setTicker(0);
clearInterval(interval);
}
return (
<div>
<span style={{ fontSize: 100 }}>{ticker}</span>
<button onClick={tick}>Tick!</button>
<button onClick={reset}>Reset</button>
</div>
);
} |
|
bbeo-css-pattern-comp-14-input |
function Ticker(props) {
const [ticker, setTicker] = React.useState(0);
let interval = null;
const tick = () => {
reset();
interval = setInterval(() => {
if (ticker < props.times)
setTicker(ticker + 1);
else
clearInterval(interval);
}, props.interval);
}
const reset = () => {
setTicker(0);
clearInterval(interval);
}
return (
<div>
<span style={{ fontSize: 100 }}>{ticker}</span>
<button onClick={tick}>Tick!</button>
<button onClick={reset}>Reset</button>
</div>
);
} |
|
bbeo-react-pattern-state-15-propsDrillingState |
function Child({ parentData }) {
return (
<div>
<span>Child data: {parentData}</span>
</div>
);
}
export default function Parent() {
const [state, setState] = React.useState(null);
const externalData = 'Ceci est un donnee venant du composant parent';
return (
<div>
<p>Parent data: {state}</p>
<Child parentData={state} />
<br />
<button onClick={() => setState(externalData)}>Send</button>
</div>
);
} |
|
bbeo-react-pattern-state-15-callbackFuncState |
function Child({ sendDatatoParent }) {
const externalData = 'Ceci est un donnee venant du composant enfant';
return (
<div>
<span>Child data: {externalData}</span>
<br />
<button onClick={() => sendDatatoParent(externalData)}>Send</button>
</div>
);
}
export default function Parent() {
const [state, setState] = React.useState(null);
const sendDatatoParent = childData => {
setState(childData);
};
return (
<div>
<p>Parent data: {state}</p>
<Child sendDatatoParent={sendDatatoParent} />
</div>
);
} |
|
bbeo-react-pattern-event-16-onClick |
export default function Age() {
let [state, setState] = React.useState();
state = { Users };
const setAge = value => {
setState((state.Users.user1.age += value));
};
return (
<React.Fragment>
<p>Age (user1): {Users.user1.age}</p>
<button onClick={() => setAge(2)}>Viellir</button>
</React.Fragment>
);
} |
|
bbeo-react-pattern-event-17-onChange |
export default function Message() {
const [message, setMessageValue] = React.useState('default message');
return (
<React.Fragment>
<textarea
cols="30"
rows="10"
placeholder={message}
onChange={e => setMessageValue(e.target.value)} // ecouteur d'evenement qui fait appel a la methode setMessageValue() a chaque modification et mettre a jour le state
></textarea>
</React.Fragment>
);
} |
|
bbeo-react-pattern-event-18-onSubmit |
export default function SampleForm() {
const handleSubmit = e => {
e.preventDefault();
alert(e.target['sample-input'].value); // get sample-input value
};
return (
<React.Fragment>
<form id="sample-form" onSubmit={handleSubmit}>
<h5>Sample form</h5>
<input
type="text"
name="sample-input"
placeholder="Entrer un texte ici ..."
/>
<ValidBtn />
</form>
</React.Fragment>
);
} |
|
βΎ CSS patterns
prefix | body | description |
---|---|---|
bbeo-css-pattern-treeviewCSS |
.tree-element {
margin: 0;
position: relative;
}
div.tree-element:before {
content: '';
position: absolute;
top: 24px;
left: 1px;
height: calc(100% - 48px);
border-left: 1px solid gray;
}
.toggler {
position: absolute;
top: 10px;
left: 0px;
width: 0;
height: 0;
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
border-left: 5px solid gray;
cursor: pointer;
}
.toggler.closed {
transform: rotate(90deg);
}
.collapsed {
display: none;
} |
|
bbeo-css-pattern-toolTipCSS |
.tooltip {
position: relative;
background: rgba(0, 0, 0, 0.7);
color: white;
visibility: hidden;
padding: 5px;
border-radius: 5px;
}
.tooltip-arrow {
position: absolute;
top: 100%;
left: 50%;
border-width: 5px;
border-style: solid;
border-color: rgba(0, 0, 0, 0.7) transparent transparent;
} |
|