Add createDirIfNotExists snippet

This commit is contained in:
Angelos Chalaris
2018-12-12 19:25:16 +02:00
parent b1f985e026
commit a2794c150e
4 changed files with 1522 additions and 1499 deletions

View File

@ -0,0 +1,14 @@
### createDirIfNotExists
Creates a directory, if it does not exist.
Use `fs.existsSync()` to check if the directory exists, `fs.mkdirSync()` to create it.
```js
const fs = require('fs');
const createDirIfNotExists = dir => !fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined;
```
```js
createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist
```

View File

@ -38,6 +38,7 @@ copyToClipboard:browser,string,advanced
countBy:array,object,intermediate
counter:browser,advanced
countOccurrences:array,intermediate
createDirIfNotExists:node,beginner
createElement:browser,utility,beginner
createEventHub:browser,event,advanced
CSVToArray:string,array,utility,intermediate

View File

@ -1,53 +1,6 @@
const fs = typeof require !== "undefined" && require('fs');
const crypto = typeof require !== "undefined" && require('crypto');
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
const JSONToFile = (obj, filename) =>
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
const JSONtoCSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
const UUIDGeneratorNode = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
const all = (arr, fn = Boolean) => arr.every(fn);
@ -166,7 +119,6 @@ const countBy = (arr, fn) =>
bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
@ -178,6 +130,9 @@ const counter = (selector, start, end, step = 1, duration = 2000) => {
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
@ -197,6 +152,21 @@ const createEventHub = () => ({
const countBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
const counter = (selector, start, end, step = 1, duration = 2000) => {
let current = start,
_step = (end - start) * step < 0 ? -step : step,
timer = setInterval(() => {
current += _step;
document.querySelector(selector).innerHTML = current;
if (current >= end) document.querySelector(selector).innerHTML = end;
if (current >= end) clearInterval(timer);
}, Math.abs(Math.floor(duration / (end - start))));
return timer;
};
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
@ -373,11 +343,6 @@ const forEachRight = (arr, callback) =>
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
const forOwnRight = (obj, fn) =>
Object.keys(obj)
.reverse()
.forEach(key => fn(obj[key], key, obj));
if (a === null || a === undefined || b === null || b === undefined) return false;
if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a);
@ -392,6 +357,11 @@ const formatDuration = ms => {
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag] || tag)
);
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@ -521,10 +491,6 @@ const hz = (fn, iterations = 100) => {
(dateFinal - dateInitial) / (1000 * 3600 * 24);
const getImages = (el, includeDuplicates = false) => {
const inRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
@ -541,6 +507,10 @@ const initializeNDArray = (val, ...args) =>
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
@ -652,6 +622,19 @@ const join = (arr, separator = ',', end = separator) =>
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
const initializeNDArray = (val, ...args) =>
args.length === 0
? val
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
const inRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
@ -784,6 +767,14 @@ const on = (el, evt, fn, opts = {}) => {
const isValidJSON = str => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
const isWritableStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._write === 'function' &&
@ -798,14 +789,6 @@ const onUserInputChange = callback => {
? acc + val
: acc + val + separator,
''
const once = fn => {
let called = false;
return function(...args) {
if (called) return;
called = true;
return fn.apply(this, args);
};
};
);
const JSONtoCSV = (arr, columns, delimiter = ',') =>
@ -965,10 +948,6 @@ const recordAnimationFrames = (callback, autoStart = true) => {
characterData: true,
characterDataOldValue: true,
subtree: true
const reduceSuccessive = (arr, fn, acc) =>
arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);
const reduceWhich = (arr, comparator = (a, b) => a - b) =>
arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
},
options
)
@ -976,6 +955,10 @@ const reducedFilter = (data, keys, fn) =>
return observer;
};
const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
const omit = (obj, arr) =>
Object.keys(obj)
.filter(k => !arr.includes(k))
@ -994,6 +977,7 @@ const renameKeys = (keysMap, obj) =>
const once = fn => {
let called = false;
return function(...args) {
if (called) return;
called = true;
return fn.apply(this, args);
@ -1168,16 +1152,16 @@ const throttle = (fn, wait) => {
return '#' + n.slice(0, 6);
};
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
const readFileLines = filename =>
fs
const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
.readFileSync(filename)
.toString('UTF8')
.split('\n');
@ -1190,6 +1174,7 @@ const toCamelCase = str => {
const stop = () => {
running = false;
cancelAnimationFrame(raf);
};
const start = () => {
running = true;
run();
@ -1202,6 +1187,14 @@ const toKebabCase = str =>
};
if (autoStart) start();
return { start, stop };
};
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
const reducedFilter = (data, keys, fn) =>
data.filter(fn).map(el =>
keys.reduce((acc, key) => {
acc[key] = el[key];
return acc;
}, {})
@ -1225,15 +1218,6 @@ const toTitleCase = str =>
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
const toggleClass = (el, className) => el.classList.toggle(className);
const tomorrow = (long = false) => {
let t = new Date();
t.setDate(t.getDate() + 1);
const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
return !long ? ret : `${ret}T00:00:00`;
};
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
@ -1318,6 +1302,24 @@ const unzipWith = (arr, fn) =>
return arr;
};
const similarity = (arr, values) => arr.filter(v => values.includes(v));
const size = val =>
Array.isArray(val)
? val.length
: val && typeof val === 'object'
? val.size || val.length || Object.keys(val).length
: typeof val === 'string'
? new Blob([val]).size
: 0;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
const sortedIndex = (arr, n) => {
@ -1340,10 +1342,6 @@ const zipWith = (...array) => {
};
const sortedLastIndexBy = (arr, n, fn) => {
const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6)));
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
};
const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
const val = fn(n);
const index = arr
@ -1434,6 +1432,10 @@ const isSimilar = (pattern, str) =>
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
@ -1506,4 +1508,4 @@ const speechSynthesis = message => {
};
const toSafeInteger = num =>
module.exports = {CSVToArray,CSVToJSON,JSONToFile,JSONtoCSV,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,counter,createElement,createEventHub,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,deepMapKeys,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterFalsy,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,inRange,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNegativeZero,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,midpoint,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reduceSuccessive,reduceWhich,reducedFilter,reject,remove,removeNonASCII,renameKeys,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toHash,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toTitleCase,toggleClass,tomorrow,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith,JSONToDate,binarySearch,celsiusToFahrenheit,cleanObj,collatz,countVowels,factors,fahrenheitToCelsius,fibonacciCountUntilNum,fibonacciUntilNum,heronArea,howManyTimes,httpDelete,httpPut,isArmstrongNumber,isSimilar,kmphToMph,levenshteinDistance,mphToKmph,pipeLog,quickSort,removeVowels,solveRPN,speechSynthesis,squareSum}
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));

View File

@ -0,0 +1,6 @@
const expect = require('expect');
const {createDirIfNotExists} = require('./_30s.js');
test('createDirIfNotExists is a Function', () => {
expect(createDirIfNotExists).toBeInstanceOf(Function);
});