Merge remote-tracking branch 'origin/master'

This commit is contained in:
Angelos Chalaris
2018-10-08 22:31:55 +03:00
14 changed files with 690 additions and 544 deletions

View File

@ -2,8 +2,9 @@
# 30 seconds of code
[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.com/30-seconds/30-seconds-of-code.svg?branch=master)](https://travis-ci.com/30-seconds/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/6ab7791fb1ea40b4a576d658fb96807f)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=30-seconds/30-seconds-of-code&utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/4b8c1e099135f2d53413/maintainability)](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![Known Vulnerabilities](https://snyk.io/test/github/30-seconds/30-seconds-of-code/badge.svg?targetFile=package.json)](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code)
> *This README is built using [markdown-builder](https://github.com/30-seconds/markdown-builder).*
[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.com/30-seconds/30-seconds-of-code.svg?branch=master)](https://travis-ci.com/30-seconds/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/6ab7791fb1ea40b4a576d658fb96807f)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=30-seconds/30-seconds-of-code&utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/4b8c1e099135f2d53413/maintainability)](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![Known Vulnerabilities](https://snyk.io/test/github/30-seconds/30-seconds-of-code/badge.svg?targetFile=package.json)](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code)
> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

15
dist/NOTICE.md vendored
View File

@ -1,15 +0,0 @@
# WARNING!
The `_30s` module is not production ready. Do NOT use it in production websites.
It is strictly for testing purposes at this moment in time. Snippets do not have
any unit tests written and will not be reliable.
Snippet names can and will change without notice between minor versions.
Given the version `0.x.y`:
* `x` indicates a snippet name change.
* `y` indicates a new snippet or fix.
If your project is not serious and you do not care about the above issues, you will want
to use the `es5` version and also include `babel-polyfill` for widest browser support.

66
dist/_30s.es5.js vendored
View File

@ -223,7 +223,7 @@
};
var atob = function atob(str) {
return new Buffer(str, 'base64').toString('binary');
return Buffer.from(str, 'base64').toString('binary');
};
var attempt = function attempt(fn) {
@ -328,7 +328,7 @@
};
var btoa = function btoa(str) {
return new Buffer(str, 'binary').toString('base64');
return Buffer.from(str, 'binary').toString('base64');
};
var byteSize = function byteSize(str) {
@ -1007,6 +1007,16 @@
return (dateFinal - dateInitial) / (1000 * 3600 * 24);
};
var getImages = function getImages(el) {
var includeDuplicates = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var images = _toConsumableArray(el.getElementsByTagName('img')).map(function (img) {
return img.getAttribute('src');
});
return includeDuplicates ? images : _toConsumableArray(new Set(images));
};
var getMeridiemSuffixOfInteger = function getMeridiemSuffixOfInteger(num) {
return num === 0 || num === 24 ? 12 + 'am' : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';
};
@ -1309,6 +1319,10 @@
return dividend % divisor === 0;
};
var isDuplexStream = function isDuplexStream(val) {
return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && _typeof(val._readableState) === 'object' && typeof val._write === 'function' && _typeof(val._writableState) === 'object';
};
var isEmpty = function isEmpty(val) {
return val == null || !(Object.keys(val) || val).length;
};
@ -1367,6 +1381,10 @@
return obj !== null && (_typeof(obj) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
};
var isReadableStream = function isReadableStream(val) {
return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && _typeof(val._readableState) === 'object';
};
var isSameDate = function isSameDate(dateA, dateB) {
return dateA.toISOString() === dateB.toISOString();
};
@ -1402,6 +1420,10 @@
}
};
var isStream = function isStream(val) {
return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function';
};
var isString = function isString(val) {
return typeof val === 'string';
};
@ -1431,6 +1453,10 @@
}
};
var isWritableStream = function isWritableStream(val) {
return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._write === 'function' && _typeof(val._writableState) === 'object';
};
var join = function join(arr) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : separator;
@ -2493,31 +2519,9 @@
};
var takeRightWhile = function takeRightWhile(arr, func) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = arr.reverse().keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var i = _step.value;
if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return arr;
return arr.reduceRight(function (acc, el) {
return func(el) ? acc : [el].concat(_toConsumableArray(acc));
}, []);
};
var takeWhile = function takeWhile(arr, func) {
@ -2655,8 +2659,7 @@
}, acc);
};
var triggerEvent = function triggerEvent(el, eventType) {
var detail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
var triggerEvent = function triggerEvent(el, eventType, detail) {
return el.dispatchEvent(new CustomEvent(eventType, {
detail: detail
}));
@ -3005,6 +3008,7 @@
exports.get = get;
exports.getColonTimeFromDate = getColonTimeFromDate;
exports.getDaysDiffBetweenDates = getDaysDiffBetweenDates;
exports.getImages = getImages;
exports.getMeridiemSuffixOfInteger = getMeridiemSuffixOfInteger;
exports.getScrollPosition = getScrollPosition;
exports.getStyle = getStyle;
@ -3048,6 +3052,7 @@
exports.isBrowser = isBrowser;
exports.isBrowserTabFocused = isBrowserTabFocused;
exports.isDivisible = isDivisible;
exports.isDuplexStream = isDuplexStream;
exports.isEmpty = isEmpty;
exports.isEven = isEven;
exports.isFunction = isFunction;
@ -3061,14 +3066,17 @@
exports.isPrime = isPrime;
exports.isPrimitive = isPrimitive;
exports.isPromiseLike = isPromiseLike;
exports.isReadableStream = isReadableStream;
exports.isSameDate = isSameDate;
exports.isSorted = isSorted;
exports.isStream = isStream;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.isTravisCI = isTravisCI;
exports.isUndefined = isUndefined;
exports.isUpperCase = isUpperCase;
exports.isValidJSON = isValidJSON;
exports.isWritableStream = isWritableStream;
exports.join = join;
exports.last = last;
exports.lcm = lcm;

File diff suppressed because one or more lines are too long

47
dist/_30s.esm.js vendored
View File

@ -72,7 +72,7 @@ const arrayToHtmlList = (arr, listID) =>
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
const atob = str => new Buffer(str, 'base64').toString('binary');
const atob = str => Buffer.from(str, 'base64').toString('binary');
const attempt = (fn, ...args) => {
try {
@ -124,7 +124,7 @@ const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
const btoa = str => new Buffer(str, 'binary').toString('base64');
const btoa = str => Buffer.from(str, 'binary').toString('base64');
const byteSize = str => new Blob([str]).size;
@ -509,6 +509,11 @@ const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
const getMeridiemSuffixOfInteger = num =>
num === 0 || num === 24
? 12 + 'am'
@ -704,6 +709,15 @@ const isBrowserTabFocused = () => !document.hidden;
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
const isDuplexStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._read === 'function' &&
typeof val._readableState === 'object' &&
typeof val._write === 'function' &&
typeof val._writableState === 'object';
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
const isEven = num => num % 2 === 0;
@ -737,6 +751,13 @@ const isPromiseLike = obj =>
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function';
const isReadableStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._read === 'function' &&
typeof val._readableState === 'object';
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
const isSorted = arr => {
@ -748,6 +769,8 @@ const isSorted = arr => {
}
};
const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
const isString = val => typeof val === 'string';
const isSymbol = val => typeof val === 'symbol';
@ -767,6 +790,13 @@ const isValidJSON = obj => {
}
};
const isWritableStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._write === 'function' &&
typeof val._writableState === 'object';
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
@ -1385,11 +1415,8 @@ const take = (arr, n = 1) => arr.slice(0, n);
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
const takeRightWhile = (arr, func) => {
for (let i of arr.reverse().keys())
if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
return arr;
};
const takeRightWhile = (arr, func) =>
arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []);
const takeWhile = (arr, func) => {
for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
@ -1492,8 +1519,8 @@ const tomorrow = (long = false) => {
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
const triggerEvent = (el, eventType, detail = undefined) =>
el.dispatchEvent(new CustomEvent(eventType, { detail: detail }));
const triggerEvent = (el, eventType, detail) =>
el.dispatchEvent(new CustomEvent(eventType, { detail }));
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
@ -1624,4 +1651,4 @@ const zipWith = (...array) => {
);
};
export { 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, 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, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, forOwn, forOwnRight, formatDuration, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, 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, isEmpty, isEven, isFunction, isLowerCase, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isPrime, isPrimitive, isPromiseLike, isSameDate, isSorted, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, join, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, 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, 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 };
export { 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, 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, 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, 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, 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, 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 };

50
dist/_30s.js vendored
View File

@ -78,7 +78,7 @@
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
const atob = str => new Buffer(str, 'base64').toString('binary');
const atob = str => Buffer.from(str, 'base64').toString('binary');
const attempt = (fn, ...args) => {
try {
@ -130,7 +130,7 @@
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
const btoa = str => new Buffer(str, 'binary').toString('base64');
const btoa = str => Buffer.from(str, 'binary').toString('base64');
const byteSize = str => new Blob([str]).size;
@ -515,6 +515,11 @@
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
const getMeridiemSuffixOfInteger = num =>
num === 0 || num === 24
? 12 + 'am'
@ -710,6 +715,15 @@
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
const isDuplexStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._read === 'function' &&
typeof val._readableState === 'object' &&
typeof val._write === 'function' &&
typeof val._writableState === 'object';
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
const isEven = num => num % 2 === 0;
@ -743,6 +757,13 @@
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function';
const isReadableStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._read === 'function' &&
typeof val._readableState === 'object';
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
const isSorted = arr => {
@ -754,6 +775,8 @@
}
};
const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
const isString = val => typeof val === 'string';
const isSymbol = val => typeof val === 'symbol';
@ -773,6 +796,13 @@
}
};
const isWritableStream = val =>
val !== null &&
typeof val === 'object' &&
typeof val.pipe === 'function' &&
typeof val._write === 'function' &&
typeof val._writableState === 'object';
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
@ -1391,11 +1421,8 @@
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
const takeRightWhile = (arr, func) => {
for (let i of arr.reverse().keys())
if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length);
return arr;
};
const takeRightWhile = (arr, func) =>
arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []);
const takeWhile = (arr, func) => {
for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
@ -1498,8 +1525,8 @@
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
const triggerEvent = (el, eventType, detail = undefined) =>
el.dispatchEvent(new CustomEvent(eventType, { detail: detail }));
const triggerEvent = (el, eventType, detail) =>
el.dispatchEvent(new CustomEvent(eventType, { detail }));
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
@ -1734,6 +1761,7 @@
exports.get = get;
exports.getColonTimeFromDate = getColonTimeFromDate;
exports.getDaysDiffBetweenDates = getDaysDiffBetweenDates;
exports.getImages = getImages;
exports.getMeridiemSuffixOfInteger = getMeridiemSuffixOfInteger;
exports.getScrollPosition = getScrollPosition;
exports.getStyle = getStyle;
@ -1777,6 +1805,7 @@
exports.isBrowser = isBrowser;
exports.isBrowserTabFocused = isBrowserTabFocused;
exports.isDivisible = isDivisible;
exports.isDuplexStream = isDuplexStream;
exports.isEmpty = isEmpty;
exports.isEven = isEven;
exports.isFunction = isFunction;
@ -1790,14 +1819,17 @@
exports.isPrime = isPrime;
exports.isPrimitive = isPrimitive;
exports.isPromiseLike = isPromiseLike;
exports.isReadableStream = isReadableStream;
exports.isSameDate = isSameDate;
exports.isSorted = isSorted;
exports.isStream = isStream;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.isTravisCI = isTravisCI;
exports.isUndefined = isUndefined;
exports.isUpperCase = isUpperCase;
exports.isValidJSON = isValidJSON;
exports.isWritableStream = isWritableStream;
exports.join = join;
exports.last = last;
exports.lcm = lcm;

View File

@ -2031,6 +2031,26 @@
"hash": "baeec5f4220f1e457b11034e29d84277dbdc9fc5c9e69c1a225bb22f13b843ec"
}
},
{
"id": "getImages",
"type": "snippet",
"attributes": {
"fileName": "getImages.md",
"text": "Fetches all images from within an element and puts them into an array\n\nUse `Element.prototype.getElementsByTagName()` to fetch all `<img>` elements inside the provided element, `Array.prototype.map()` to map every `src` attribute of their respective `<img>` element, then create a `Set` to eliminate duplicates and return the array.",
"codeBlocks": [
"const getImages = (el, includeDuplicates = false) => {\n const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));\n return includeDuplicates ? images : [...new Set(images)];\n};",
"getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']\ngetImages(document, false); // ['image1.jpg', 'image2.png', '...']"
],
"tags": [
"browser",
"beginner"
]
},
"meta": {
"archived": false,
"hash": "0f2ba02c6de1e9396abbef584139bea4dc379a6d465f4bebb151ad3b0f77ff6f"
}
},
{
"id": "getMeridiemSuffixOfInteger",
"type": "snippet",

View File

@ -119,6 +119,23 @@
"hash": "9de50bed5b8c247176570f743c8154a5ec4093432f8a09ba91c423d78af47169"
}
},
{
"id": "heronArea",
"type": "snippet",
"attributes": {
"fileName": "heronArea.md",
"text": "Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.\n\nMore information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.\n\nUses `Math.sqrt()` to find the square root of a value.",
"codeBlocks": [
"const heronArea = (side_a, side_b, side_c) => {\n const p = (side_a + side_b + side_c) / 2\n return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n };",
"heronArea(3, 4, 5); // 6"
],
"tags": []
},
"meta": {
"archived": true,
"hash": "594721a84a8fe31c32482e9f475f5126b7cf499462d9408b3cfaee2021a96a30"
}
},
{
"id": "howManyTimes",
"type": "snippet",
@ -297,8 +314,10 @@
"fibonacciCountUntilNum(10); // 7",
"const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};",
"fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]",
"const howManyTimes = (num, divisor) => {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n let i = 0;\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n return i;\n};",
"howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity",
"const heronArea = (side_a, side_b, side_c) => {\n const p = (side_a + side_b + side_c) / 2\n return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n };",
"heronArea(3, 4, 5); // 6",
"const httpDelete = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send();\n};",
"httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'",
"const httpPut = (url, data, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type','application/json; charset=utf-8');\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send(data);\n};",
"const password = \"fooBaz\";\nconst data = JSON.stringify(password);\nhttpPut('https://website.com/users/123', data, request => {\n console.log(request.responseText);\n}); // 'Updates a user's password in database'",
"const isArmstrongNumber = digits =>\n (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n (digits + '').split('')\n );",
@ -315,14 +334,14 @@
"removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\"",
"const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
"solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8",
"const httpDelete = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send();\n};",
"httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'"
"const howManyTimes = (num, divisor) => {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n let i = 0;\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n return i;\n};",
"howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity"
],
"tags": []
},
"meta": {
"archived": true,
"hash": "923a1f48f03450680f6150058f7ae52edf8a08a0d00d57cf26aa803f707643c9"
"hash": "50abe1eb4fadd6d7d8ab5c5dc027f0bf34e6c391b6da1367ddee907abd741a30"
}
},
{

View File

@ -11,7 +11,8 @@ These snippets, while useful and interesting, didn't quite make it into the repo
* [`factors`](#factors)
* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
* [`fibonacciUntilNum`](#fibonacciuntilnum)
* [`howManyTimes`](#howmanytimes)
* [`heronArea`](#heronarea)
* [`httpDelete`](#httpdelete)
* [`httpPut`](#httpput)
* [`isArmstrongNumber`](#isarmstrongnumber)
* [`isSimilar`](#issimilar)
@ -20,7 +21,7 @@ These snippets, while useful and interesting, didn't quite make it into the repo
* [`quickSort`](#quicksort)
* [`removeVowels`](#removevowels)
* [`solveRPN`](#solverpn)
* [`httpDelete`](#httpdelete)
* [`howManyTimes`](#howmanytimes)
---
### JSONToDate
@ -283,26 +284,49 @@ fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
<br>[⬆ Back to top](#table-of-contents)
### howManyTimes
### heronArea
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
Works for both negative and positive integers.
Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.
More information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.
Uses `Math.sqrt()` to find the square root of a value.
If `divisor` is `-1` or `1` return `Infinity`.
If `divisor` is `-0` or `0` return `0`.
Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.
Return the number of times the loop was executed, `i`.
```js
const howManyTimes = (num, divisor) => {
if (divisor === 1 || divisor === -1) return Infinity;
if (divisor === 0) return 0;
let i = 0;
while (Number.isInteger(num / divisor)) {
i++;
num = num / divisor;
}
return i;
const heronArea = (side_a, side_b, side_c) => {
const p = (side_a + side_b + side_c) / 2
return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
};
```
<details>
<summary>Examples</summary>
```js
heronArea(3, 4, 5); // 6
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### httpDelete
Makes a `DELETE` request to the passed URL.
Use `XMLHttpRequest` web api to make a `delete` request to the given `url`.
Handle the `onload` event, by running the provided `callback` function.
Handle the `onerror` event, by running the provided `err` function.
Omit the third argument, `err` to log the request to the console's error stream by default.
```js
const httpDelete = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('DELETE', url, true);
request.onload = () => callback(request);
request.onerror = () => err(request);
request.send();
};
```
@ -310,10 +334,9 @@ const howManyTimes = (num, divisor) => {
<summary>Examples</summary>
```js
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
howManyTimes(100, -1); // Infinity
httpDelete('https://website.com/users/123', request => {
console.log(request.responseText);
}); // 'Deletes a user from the database'
```
</details>
@ -588,22 +611,26 @@ solveRPN('2 3 ^'); // 8
<br>[⬆ Back to top](#table-of-contents)
### httpDelete
### howManyTimes
Makes a `DELETE` request to the passed URL.
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
Works for both negative and positive integers.
Use `XMLHttpRequest` web api to make a `delete` request to the given `url`.
Handle the `onload` event, by running the provided `callback` function.
Handle the `onerror` event, by running the provided `err` function.
Omit the third argument, `err` to log the request to the console's error stream by default.
If `divisor` is `-1` or `1` return `Infinity`.
If `divisor` is `-0` or `0` return `0`.
Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.
Return the number of times the loop was executed, `i`.
```js
const httpDelete = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('DELETE', url, true);
request.onload = () => callback(request);
request.onerror = () => err(request);
request.send();
const howManyTimes = (num, divisor) => {
if (divisor === 1 || divisor === -1) return Infinity;
if (divisor === 0) return 0;
let i = 0;
while (Number.isInteger(num / divisor)) {
i++;
num = num / divisor;
}
return i;
};
```
@ -611,9 +638,10 @@ const httpDelete = (url, callback, err = console.error) => {
<summary>Examples</summary>
```js
httpDelete('https://website.com/users/123', request => {
console.log(request.responseText);
}); // 'Deletes a user from the database'
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
howManyTimes(100, -1); // Infinity
```
</details>

View File

@ -2,8 +2,9 @@
# 30 seconds of code
[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.com/30-seconds/30-seconds-of-code.svg?branch=master)](https://travis-ci.com/30-seconds/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/6ab7791fb1ea40b4a576d658fb96807f)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=30-seconds/30-seconds-of-code&amp;utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/4b8c1e099135f2d53413/maintainability)](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![Known Vulnerabilities](https://snyk.io/test/github/30-seconds/30-seconds-of-code/badge.svg?targetFile=package.json)](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code)
> *This README is built using [markdown-builder](https://github.com/30-seconds/markdown-builder).*
[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.com/30-seconds/30-seconds-of-code.svg?branch=master)](https://travis-ci.com/30-seconds/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/6ab7791fb1ea40b4a576d658fb96807f)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=30-seconds/30-seconds-of-code&amp;utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/4b8c1e099135f2d53413/maintainability)](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![Known Vulnerabilities](https://snyk.io/test/github/30-seconds/30-seconds-of-code/badge.svg?targetFile=package.json)](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code)
> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

View File

@ -1,5 +1,5 @@
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName("img")].map(img => img.getAttribute("src"));
return includeDuplicates ? images : [...(new Set(images))];
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
module.exports = getImages;

View File

@ -0,0 +1,5 @@
const heronArea = (side_a, side_b, side_c) => {
const p = (side_a + side_b + side_c) / 2
return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
};
module.exports = heronArea;

View File

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

File diff suppressed because it is too large Load Diff