Merge pull request #1 from 30-seconds/master

update
This commit is contained in:
itchylol742
2018-11-10 16:54:07 -05:00
committed by GitHub
81 changed files with 3690 additions and 2660 deletions

5
.gitignore vendored
View File

@ -4,9 +4,8 @@ currentSnippet\.js
.idea
test.sh
/*.log
dist/flavor\.min\.css
dist/flavor\.css
test_old/
coverage/clover.xml
coverage/lcov-report

View File

@ -9,11 +9,19 @@ CODE_OF_CONDUCT.md
.mdlrc
.codeclimate.yml
test/*
glossary/*
snippets/*
static-parts/*
snippet_data/*
snippets_archive/*
scripts/*
locale/*
coverage/*
docs/*
.travis/*
.github/*
advanced.svg
package-lock.json
yarn.lock
advanced.svg
sponsored_by_DigitalOcean.png

View File

@ -13,6 +13,7 @@ script:
- npm run linter
- npm run packager
- npm run tester
- npm run test-with-coverage
- npm run extractor
- npm run vscoder
- npm run glossary:keymaker

View File

@ -15,6 +15,7 @@ commit_website_files() {
elif [ $TRAVIS_EVENT_TYPE == "api" ]; then
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]"
else
git reset coverage/*
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER"
fi
fi

View File

@ -2806,7 +2806,7 @@ const toHash = (object, key) =>
<summary>Examples</summary>
```js
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 }
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }
toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }
// A more in depth example:
let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];
@ -3647,7 +3647,7 @@ Hides all the elements specified.
Use `NodeList.prototype.forEach()` to apply `display: none` to each element specified.
```js
const hide = els => els.forEach(e => (e.style.display = 'none'));
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
```
<details>

File diff suppressed because one or more lines are too long

3020
coverage/lcov.info Normal file

File diff suppressed because it is too large Load Diff

120
dist/_30s.es5.js vendored
View File

@ -1101,8 +1101,12 @@
return 'rgb' + (alpha ? 'a' : '') + '(' + (h >>> (alpha ? 24 : 16)) + ', ' + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + (alpha ? ", ".concat(h & 0x000000ff) : '') + ')';
};
var hide = function hide(els) {
return els.forEach(function (e) {
var hide = function hide() {
for (var _len27 = arguments.length, el = new Array(_len27), _key27 = 0; _key27 < _len27; _key27++) {
el[_key27] = arguments[_key27];
}
return el.concat().forEach(function (e) {
return e.style.display = 'none';
});
};
@ -1219,8 +1223,8 @@
};
var initializeNDArray = function initializeNDArray(val) {
for (var _len27 = arguments.length, args = new Array(_len27 > 1 ? _len27 - 1 : 0), _key27 = 1; _key27 < _len27; _key27++) {
args[_key27 - 1] = arguments[_key27];
for (var _len28 = arguments.length, args = new Array(_len28 > 1 ? _len28 - 1 : 0), _key28 = 1; _key28 < _len28; _key28++) {
args[_key28 - 1] = arguments[_key28];
}
return args.length === 0 ? val : Array.from({
@ -1472,8 +1476,8 @@
return x * y / gcd(x, y);
};
for (var _len28 = arguments.length, arr = new Array(_len28), _key28 = 0; _key28 < _len28; _key28++) {
arr[_key28] = arguments[_key28];
for (var _len29 = arguments.length, arr = new Array(_len29), _key29 = 0; _key29 < _len29; _key29++) {
arr[_key29] = arguments[_key29];
}
return arr.concat().reduce(function (a, b) {
@ -1482,8 +1486,8 @@
};
var longestItem = function longestItem() {
for (var _len29 = arguments.length, vals = new Array(_len29), _key29 = 0; _key29 < _len29; _key29++) {
vals[_key29] = arguments[_key29];
for (var _len30 = arguments.length, vals = new Array(_len30), _key30 = 0; _key30 < _len30; _key30++) {
vals[_key30] = arguments[_key30];
}
return vals.reduce(function (a, x) {
@ -1565,8 +1569,8 @@
var maxDate = function maxDate() {
var _Math$max;
for (var _len30 = arguments.length, dates = new Array(_len30), _key30 = 0; _key30 < _len30; _key30++) {
dates[_key30] = arguments[_key30];
for (var _len31 = arguments.length, dates = new Array(_len31), _key31 = 0; _key31 < _len31; _key31++) {
dates[_key31] = arguments[_key31];
}
return new Date((_Math$max = Math.max).apply.apply(_Math$max, [null].concat(dates)));
@ -1600,8 +1604,8 @@
};
var merge = function merge() {
for (var _len31 = arguments.length, objs = new Array(_len31), _key31 = 0; _key31 < _len31; _key31++) {
objs[_key31] = arguments[_key31];
for (var _len32 = arguments.length, objs = new Array(_len32), _key32 = 0; _key32 < _len32; _key32++) {
objs[_key32] = arguments[_key32];
}
return objs.concat().reduce(function (acc, obj) {
@ -1621,8 +1625,8 @@
var minDate = function minDate() {
var _Math$min;
for (var _len32 = arguments.length, dates = new Array(_len32), _key32 = 0; _key32 < _len32; _key32++) {
dates[_key32] = arguments[_key32];
for (var _len33 = arguments.length, dates = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) {
dates[_key33] = arguments[_key33];
}
return new Date((_Math$min = Math.min).apply.apply(_Math$min, [null].concat(dates)));
@ -1678,8 +1682,8 @@
var nthArg = function nthArg(n) {
return function () {
for (var _len33 = arguments.length, args = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) {
args[_key33] = arguments[_key33];
for (var _len34 = arguments.length, args = new Array(_len34), _key34 = 0; _key34 < _len34; _key34++) {
args[_key34] = arguments[_key34];
}
return args.slice(n)[0];
@ -1782,8 +1786,8 @@
if (called) return;
called = true;
for (var _len34 = arguments.length, args = new Array(_len34), _key34 = 0; _key34 < _len34; _key34++) {
args[_key34] = arguments[_key34];
for (var _len35 = arguments.length, args = new Array(_len35), _key35 = 0; _key35 < _len35; _key35++) {
args[_key35] = arguments[_key35];
}
return fn.apply(this, args);
@ -1808,13 +1812,13 @@
};
var over = function over() {
for (var _len35 = arguments.length, fns = new Array(_len35), _key35 = 0; _key35 < _len35; _key35++) {
fns[_key35] = arguments[_key35];
for (var _len36 = arguments.length, fns = new Array(_len36), _key36 = 0; _key36 < _len36; _key36++) {
fns[_key36] = arguments[_key36];
}
return function () {
for (var _len36 = arguments.length, args = new Array(_len36), _key36 = 0; _key36 < _len36; _key36++) {
args[_key36] = arguments[_key36];
for (var _len37 = arguments.length, args = new Array(_len37), _key37 = 0; _key37 < _len37; _key37++) {
args[_key37] = arguments[_key37];
}
return fns.map(function (fn) {
@ -1825,8 +1829,8 @@
var overArgs = function overArgs(fn, transforms) {
return function () {
for (var _len37 = arguments.length, args = new Array(_len37), _key37 = 0; _key37 < _len37; _key37++) {
args[_key37] = arguments[_key37];
for (var _len38 = arguments.length, args = new Array(_len38), _key38 = 0; _key38 < _len38; _key38++) {
args[_key38] = arguments[_key38];
}
return fn.apply(void 0, _toConsumableArray(args.map(function (val, i) {
@ -1855,13 +1859,13 @@
};
var partial = function partial(fn) {
for (var _len38 = arguments.length, partials = new Array(_len38 > 1 ? _len38 - 1 : 0), _key38 = 1; _key38 < _len38; _key38++) {
partials[_key38 - 1] = arguments[_key38];
for (var _len39 = arguments.length, partials = new Array(_len39 > 1 ? _len39 - 1 : 0), _key39 = 1; _key39 < _len39; _key39++) {
partials[_key39 - 1] = arguments[_key39];
}
return function () {
for (var _len39 = arguments.length, args = new Array(_len39), _key39 = 0; _key39 < _len39; _key39++) {
args[_key39] = arguments[_key39];
for (var _len40 = arguments.length, args = new Array(_len40), _key40 = 0; _key40 < _len40; _key40++) {
args[_key40] = arguments[_key40];
}
return fn.apply(void 0, partials.concat(args));
@ -1869,13 +1873,13 @@
};
var partialRight = function partialRight(fn) {
for (var _len40 = arguments.length, partials = new Array(_len40 > 1 ? _len40 - 1 : 0), _key40 = 1; _key40 < _len40; _key40++) {
partials[_key40 - 1] = arguments[_key40];
for (var _len41 = arguments.length, partials = new Array(_len41 > 1 ? _len41 - 1 : 0), _key41 = 1; _key41 < _len41; _key41++) {
partials[_key41 - 1] = arguments[_key41];
}
return function () {
for (var _len41 = arguments.length, args = new Array(_len41), _key41 = 0; _key41 < _len41; _key41++) {
args[_key41] = arguments[_key41];
for (var _len42 = arguments.length, args = new Array(_len42), _key42 = 0; _key42 < _len42; _key42++) {
args[_key42] = arguments[_key42];
}
return fn.apply(void 0, args.concat(partials));
@ -1919,8 +1923,8 @@
};
var pipeAsyncFunctions = function pipeAsyncFunctions() {
for (var _len42 = arguments.length, fns = new Array(_len42), _key42 = 0; _key42 < _len42; _key42++) {
fns[_key42] = arguments[_key42];
for (var _len43 = arguments.length, fns = new Array(_len43), _key43 = 0; _key43 < _len43; _key43++) {
fns[_key43] = arguments[_key43];
}
return function (arg) {
@ -1931,8 +1935,8 @@
};
var pipeFunctions = function pipeFunctions() {
for (var _len43 = arguments.length, fns = new Array(_len43), _key43 = 0; _key43 < _len43; _key43++) {
fns[_key43] = arguments[_key43];
for (var _len44 = arguments.length, fns = new Array(_len44), _key44 = 0; _key44 < _len44; _key44++) {
fns[_key44] = arguments[_key44];
}
return fns.reduce(function (f, g) {
@ -2005,8 +2009,8 @@
var promisify = function promisify(func) {
return function () {
for (var _len44 = arguments.length, args = new Array(_len44), _key44 = 0; _key44 < _len44; _key44++) {
args[_key44] = arguments[_key44];
for (var _len45 = arguments.length, args = new Array(_len45), _key45 = 0; _key45 < _len45; _key45++) {
args[_key45] = arguments[_key45];
}
return new Promise(function (resolve, reject) {
@ -2018,8 +2022,8 @@
};
var pull = function pull(arr) {
for (var _len45 = arguments.length, args = new Array(_len45 > 1 ? _len45 - 1 : 0), _key45 = 1; _key45 < _len45; _key45++) {
args[_key45 - 1] = arguments[_key45];
for (var _len46 = arguments.length, args = new Array(_len46 > 1 ? _len46 - 1 : 0), _key46 = 1; _key46 < _len46; _key46++) {
args[_key46 - 1] = arguments[_key46];
}
var argState = Array.isArray(args[0]) ? args[0] : args;
@ -2062,8 +2066,8 @@
};
var pullBy = function pullBy(arr) {
for (var _len46 = arguments.length, args = new Array(_len46 > 1 ? _len46 - 1 : 0), _key46 = 1; _key46 < _len46; _key46++) {
args[_key46 - 1] = arguments[_key46];
for (var _len47 = arguments.length, args = new Array(_len47 > 1 ? _len47 - 1 : 0), _key47 = 1; _key47 < _len47; _key47++) {
args[_key47 - 1] = arguments[_key47];
}
var length = args.length;
@ -2113,8 +2117,8 @@
var rearg = function rearg(fn, indexes) {
return function () {
for (var _len47 = arguments.length, args = new Array(_len47), _key47 = 0; _key47 < _len47; _key47++) {
args[_key47] = arguments[_key47];
for (var _len48 = arguments.length, args = new Array(_len48), _key48 = 0; _key48 < _len48; _key48++) {
args[_key48] = arguments[_key48];
}
return fn.apply(void 0, _toConsumableArray(indexes.map(function (i) {
@ -2288,16 +2292,16 @@
var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var delCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
for (var _len48 = arguments.length, elements = new Array(_len48 > 3 ? _len48 - 3 : 0), _key48 = 3; _key48 < _len48; _key48++) {
elements[_key48 - 3] = arguments[_key48];
for (var _len49 = arguments.length, elements = new Array(_len49 > 3 ? _len49 - 3 : 0), _key49 = 3; _key49 < _len49; _key49++) {
elements[_key49 - 3] = arguments[_key49];
}
return arr.slice(0, index).concat(elements).concat(arr.slice(index + delCount));
};
var show = function show() {
for (var _len49 = arguments.length, el = new Array(_len49), _key49 = 0; _key49 < _len49; _key49++) {
el[_key49] = arguments[_key49];
for (var _len50 = arguments.length, el = new Array(_len50), _key50 = 0; _key50 < _len50; _key50++) {
el[_key50] = arguments[_key50];
}
return el.concat().forEach(function (e) {
@ -2433,8 +2437,8 @@
};
var sum = function sum() {
for (var _len50 = arguments.length, arr = new Array(_len50), _key50 = 0; _key50 < _len50; _key50++) {
arr[_key50] = arguments[_key50];
for (var _len51 = arguments.length, arr = new Array(_len51), _key51 = 0; _key51 < _len51; _key51++) {
arr[_key51] = arguments[_key51];
}
return arr.concat().reduce(function (acc, val) {
@ -2690,8 +2694,8 @@
};
};
for (var _len51 = arguments.length, args = new Array(_len51), _key51 = 0; _key51 < _len51; _key51++) {
args[_key51] = arguments[_key51];
for (var _len52 = arguments.length, args = new Array(_len52), _key52 = 0; _key52 < _len52; _key52++) {
args[_key52] = arguments[_key52];
}
if (n > args.length) throw new RangeError('Arguments too few!');
@ -2829,8 +2833,8 @@
};
var without = function without(arr) {
for (var _len52 = arguments.length, args = new Array(_len52 > 1 ? _len52 - 1 : 0), _key52 = 1; _key52 < _len52; _key52++) {
args[_key52 - 1] = arguments[_key52];
for (var _len53 = arguments.length, args = new Array(_len53 > 1 ? _len53 - 1 : 0), _key53 = 1; _key53 < _len53; _key53++) {
args[_key53 - 1] = arguments[_key53];
}
return arr.filter(function (v) {
@ -2857,8 +2861,8 @@
};
var zip = function zip() {
for (var _len53 = arguments.length, arrays = new Array(_len53), _key53 = 0; _key53 < _len53; _key53++) {
arrays[_key53] = arguments[_key53];
for (var _len54 = arguments.length, arrays = new Array(_len54), _key54 = 0; _key54 < _len54; _key54++) {
arrays[_key54] = arguments[_key54];
}
var maxLength = Math.max.apply(Math, _toConsumableArray(arrays.map(function (x) {
@ -2882,8 +2886,8 @@
};
var zipWith = function zipWith() {
for (var _len54 = arguments.length, array = new Array(_len54), _key54 = 0; _key54 < _len54; _key54++) {
array[_key54] = arguments[_key54];
for (var _len55 = arguments.length, array = new Array(_len55), _key55 = 0; _key55 < _len55; _key55++) {
array[_key55] = arguments[_key55];
}
var fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;

File diff suppressed because one or more lines are too long

2
dist/_30s.esm.js vendored
View File

@ -482,7 +482,7 @@ const hexToRGB = hex => {
')'
);
};
const hide = els => els.forEach(e => (e.style.display = 'none'));
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
const httpGet = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);

2
dist/_30s.js vendored
View File

@ -488,7 +488,7 @@
')'
);
};
const hide = els => els.forEach(e => (e.style.display = 'none'));
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
const httpGet = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);

View File

@ -217,7 +217,7 @@ hub<span class="token punctuation">.</span><span class="token function">off</spa
<span class="token keyword">return</span> hexes<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">);
});</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hashBrowser</span><span class="token punctuation">(</span><span class="token constant">JSON</span><span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">({</span> a<span class="token punctuation">:</span> <span class="token string">'a'</span><span class="token punctuation">,</span> b<span class="token punctuation">: [</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">],</span> foo<span class="token punctuation">: {</span> c<span class="token punctuation">:</span> <span class="token string">'bar'</span> <span class="token punctuation">} })).</span><span class="token function">then</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="hide">hide</h4><p>Hides all the elements specified.</p><p>Use <code>NodeList.prototype.forEach()</code> to apply <code>display: none</code> to each element specified.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hide</span> <span class="token operator">=</span> els <span class="token operator">=></span> els<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>e <span class="token operator">=></span> <span class="token punctuation">(</span>e<span class="token punctuation">.</span>style<span class="token punctuation">.</span>display <span class="token operator">=</span> <span class="token string">'none'</span><span class="token punctuation">));</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="hide">hide</h4><p>Hides all the elements specified.</p><p>Use <code>NodeList.prototype.forEach()</code> to apply <code>display: none</code> to each element specified.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hide</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">...</span>el<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">[</span><span class="token operator">...</span>el<span class="token punctuation">].</span><span class="token function">forEach</span><span class="token punctuation">(</span>e <span class="token operator">=></span> <span class="token punctuation">(</span>e<span class="token punctuation">.</span>style<span class="token punctuation">.</span>display <span class="token operator">=</span> <span class="token string">'none'</span><span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hide</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span><span class="token string">'img'</span><span class="token punctuation">));</span> <span class="token comment">// Hides all &lt;img> elements on the page</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="httpsredirect">httpsRedirect</h4><p>Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.</p><p>Use <code>location.protocol</code> to get the protocol currently being used. If it's not HTTPS, use <code>location.replace()</code> to replace the existing page with the HTTPS version of the page. Use <code>location.href</code> to get the full address, split it with <code>String.prototype.split()</code> and remove the protocol part of the URL.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpsRedirect</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>location<span class="token punctuation">.</span>protocol <span class="token operator">!==</span> <span class="token string">'https:'</span><span class="token punctuation">)</span> location<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token string">'https://'</span> <span class="token operator">+</span> location<span class="token punctuation">.</span>href<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">'//'</span><span class="token punctuation">)[</span><span class="token number">1</span><span class="token punctuation">]);

View File

@ -526,7 +526,7 @@ console<span class="token punctuation">.</span><span class="token function">log<
(</span>acc<span class="token punctuation">,</span> data<span class="token punctuation">,</span> index<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">((</span>acc<span class="token punctuation">[</span><span class="token operator">!</span>key <span class="token operator">?</span> index <span class="token punctuation">:</span> data<span class="token punctuation">[</span>key<span class="token punctuation">]]</span> <span class="token operator">=</span> data<span class="token punctuation">),</span> acc<span class="token punctuation">),
{}
);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toHash</span><span class="token punctuation">([</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">]);</span> <span class="token comment">// { 0: 4, 1: 3, 2: 2, 1: 1 }</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toHash</span><span class="token punctuation">([</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">]);</span> <span class="token comment">// { 0: 4, 1: 3, 2: 2, 3: 1 }</span>
<span class="token function">toHash</span><span class="token punctuation">([{</span> a<span class="token punctuation">:</span> <span class="token string">'label'</span> <span class="token punctuation">}],</span> <span class="token string">'a'</span><span class="token punctuation">);</span> <span class="token comment">// { label: { a: 'label' } }</span>
<span class="token comment">// A more in depth example:</span>
<span class="token keyword">let</span> users <span class="token operator">=</span> <span class="token punctuation">[{</span> id<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span> first<span class="token punctuation">:</span> <span class="token string">'Jon'</span> <span class="token punctuation">}, {</span> id<span class="token punctuation">:</span> <span class="token number">2</span><span class="token punctuation">,</span> first<span class="token punctuation">:</span> <span class="token string">'Joe'</span> <span class="token punctuation">}, {</span> id<span class="token punctuation">:</span> <span class="token number">3</span><span class="token punctuation">,</span> first<span class="token punctuation">:</span> <span class="token string">'Moe'</span> <span class="token punctuation">}];</span>

2
package-lock.json generated
View File

@ -1,6 +1,6 @@
{
"name": "30-seconds-of-code",
"version": "1.1.0",
"version": "1.2.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@ -8,7 +8,6 @@
"fs-extra": "^6.0.0",
"html-minifier": "^3.5.20",
"jest": "^23.6.0",
"jest-tap-reporter": "^1.9.0",
"markdown-builder": "^0.8.4",
"markdown-it": "^8.4.2",
"node-sass": "^4.9.3",
@ -21,9 +20,10 @@
},
"name": "30-seconds-of-code",
"description": "A collection of useful JavaScript snippets.",
"version": "1.1.0",
"version": "1.2.2",
"main": "dist/_30s.js",
"module": "dist/_30s.esm.js",
"sideEffects": false,
"scripts": {
"glossary:librarian": "node ./scripts/glossary/library.js",
"glossary:keymaker": "node ./scripts/glossary/keyword.js",
@ -36,7 +36,7 @@
"vscoder": "node ./scripts/vscodegen.js",
"packager": "node ./scripts/module.js",
"localizer": "node ./scripts/localize.js",
"test": "jest --verbose",
"test": "jest --verbose --coverage",
"test-with-coverage": "jest --coverage && cat ./coverage/lcov.info | codacy-coverage"
},
"repository": {
@ -53,18 +53,6 @@
"bugs": {
"url": "https://github.com/30-seconds/30-seconds-of-code/issues"
},
"homepage": "https://github.com/30-seconds/30-seconds-of-code#readme",
"dependencies": {},
"jest": {
"reporters": [
[
"jest-tap-reporter",
{
"logLevel": "INFO",
"showInternalStackTraces": false,
"filePath": "test/testlog"
}
]
]
}
"homepage": "https://30secondsofcode.org/",
"dependencies": {}
}

View File

@ -47,8 +47,7 @@ if (
// Store the data read from each snippet in the appropriate object
for (const name of snippetFilenames.filter(s => s !== 'README.md'))
snippets[name] = fs.readFileSync(path.join(SNIPPETS_ARCHIVE_PATH, name), 'utf8');
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`);
process.exit(1);
}
@ -70,8 +69,7 @@ if (
// Write to the README file of the archive
fs.writeFileSync(path.join(SNIPPETS_ARCHIVE_PATH, 'README.md'), output);
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During README generation for snippets archive: ${err}`);
process.exit(1);
}
@ -110,8 +108,7 @@ snippets = util.readSnippets(SNIPPETS_PATH);
try {
startPart = fs.readFileSync(path.join(STATIC_PARTS_PATH, 'README-start.md'), 'utf8');
endPart = fs.readFileSync(path.join(STATIC_PARTS_PATH, 'README-end.md'), 'utf8');
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During static part loading: ${err}`);
process.exit(1);
}
@ -171,8 +168,7 @@ try {
output += `\n${endPart}\n`;
// Write to the README file
fs.writeFileSync('README.md', output);
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During README generation: ${err}`);
process.exit(1);
}

View File

@ -1,94 +1,93 @@
/*
This is the extractor script that generates the snippets.json and snippetsArchive.json files.
Run using `npm run extractor`.
*/
// Load modules
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
const util = require('./util');
// Paths
const SNIPPETS_PATH = './snippets';
const SNIPPETS_ARCHIVE_PATH = './snippets_archive';
const OUTPUT_PATH = './snippet_data';
// Check if running on Travis - only build for cron jobs and custom builds
if (
util.isTravisCI() &&
process.env['TRAVIS_EVENT_TYPE'] !== 'cron' &&
process.env['TRAVIS_EVENT_TYPE'] !== 'api'
) {
console.log(`${chalk.green('NOBUILD')} snippet extraction terminated, not a cron or api build!`);
process.exit(0);
}
// Read data
let snippets = {},
archivedSnippets = {},
tagDbData = {};
console.time('Extractor');
snippets = util.readSnippets(SNIPPETS_PATH);
archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
tagDbData = util.readTags();
// Extract snippet data
let snippetData = Object.keys(snippets).map(key => {
return {
id: key.slice(0, -3),
type: 'snippet',
attributes: {
fileName: key,
text: util.getTextualContent(snippets[key]).trim(),
codeBlocks: util.getCodeBlocks(snippets[key]),
tags: tagDbData[key.slice(0, -3)]
},
meta: {
archived: false,
hash: util.hashData(snippets[key])
}
};
});
// Extract archived snippet data
let snippetArchiveData = Object.keys(archivedSnippets).map(key => {
return {
id: key.slice(0, -3),
type: 'snippet',
attributes: {
fileName: key,
text: util.getTextualContent(archivedSnippets[key]).trim(),
codeBlocks: util.getCodeBlocks(archivedSnippets[key]),
tags: []
},
meta: {
archived: true,
hash: util.hashData(archivedSnippets[key])
}
};
});
const completeData = {
data: [...snippetData, ...snippetArchiveData],
meta: {
specification: 'http://jsonapi.org/format/'
}
};
let listingData = {
data:
completeData.data.map(v => ({
id: v.id,
type: 'snippetListing',
attributes: {
tags: v.attributes.tags,
archived: v.meta.archived
},
meta: {
hash: v.meta.hash
}
}))
,
meta: {
specification: 'http://jsonapi.org/format/'
}
};
// Write files
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippets.json'), JSON.stringify(completeData, null, 2));
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippetList.json'), JSON.stringify(listingData, null, 2));
// Display messages and time
console.log(`${chalk.green('SUCCESS!')} snippets.json and snippetList.json files generated!`);
console.timeEnd('Extractor');
/*
This is the extractor script that generates the snippets.json and snippetsArchive.json files.
Run using `npm run extractor`.
*/
// Load modules
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
const util = require('./util');
// Paths
const SNIPPETS_PATH = './snippets';
const SNIPPETS_ARCHIVE_PATH = './snippets_archive';
const OUTPUT_PATH = './snippet_data';
// Check if running on Travis - only build for cron jobs and custom builds
if (
util.isTravisCI() &&
process.env['TRAVIS_EVENT_TYPE'] !== 'cron' &&
process.env['TRAVIS_EVENT_TYPE'] !== 'api'
) {
console.log(`${chalk.green('NOBUILD')} snippet extraction terminated, not a cron or api build!`);
process.exit(0);
}
// Read data
let snippets = {},
archivedSnippets = {},
tagDbData = {};
console.time('Extractor');
snippets = util.readSnippets(SNIPPETS_PATH);
archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
tagDbData = util.readTags();
// Extract snippet data
let snippetData = Object.keys(snippets).map(key => {
return {
id: key.slice(0, -3),
type: 'snippet',
attributes: {
fileName: key,
text: util.getTextualContent(snippets[key]).trim(),
codeBlocks: util.getCodeBlocks(snippets[key]),
tags: tagDbData[key.slice(0, -3)]
},
meta: {
archived: false,
hash: util.hashData(snippets[key])
}
};
});
// Extract archived snippet data
let snippetArchiveData = Object.keys(archivedSnippets).map(key => {
return {
id: key.slice(0, -3),
type: 'snippet',
attributes: {
fileName: key,
text: util.getTextualContent(archivedSnippets[key]).trim(),
codeBlocks: util.getCodeBlocks(archivedSnippets[key]),
tags: []
},
meta: {
archived: true,
hash: util.hashData(archivedSnippets[key])
}
};
});
const completeData = {
data: [...snippetData, ...snippetArchiveData],
meta: {
specification: 'http://jsonapi.org/format/'
}
};
let listingData = {
data:
completeData.data.map(v => ({
id: v.id,
type: 'snippetListing',
attributes: {
tags: v.attributes.tags,
archived: v.meta.archived
},
meta: {
hash: v.meta.hash
}
})),
meta: {
specification: 'http://jsonapi.org/format/'
}
};
// Write files
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippets.json'), JSON.stringify(completeData, null, 2));
fs.writeFileSync(path.join(OUTPUT_PATH, 'snippetList.json'), JSON.stringify(listingData, null, 2));
// Display messages and time
console.log(`${chalk.green('SUCCESS!')} snippets.json and snippetList.json files generated!`);

View File

@ -41,9 +41,9 @@ const getTermLinkMarkdownBlock = termTitle => {
};
const glossaryTableOfContentsReducer = (accumulator, currentFile) => {
if (accumulator === fileTitles[0]) {
if (accumulator === fileTitles[0])
return getTermLinkMarkdownBlock(accumulator) + getTermLinkMarkdownBlock(currentFile);
}
return accumulator + getTermLinkMarkdownBlock(currentFile);
};

View File

@ -77,8 +77,7 @@ try {
console.log(`${chalk.green('SUCCESS!')} Snippet files linted!`);
console.timeEnd('Linter');
});
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During linting: ${err}`);
process.exit(1);
}

View File

@ -1,7 +1,7 @@
/*
Builds the `_30s` module.
*/
// Load modules
/**
* Builds the `_30s` module in UMD and ESM formats.
* Also builds the test module file for testing snippets.
*/
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
@ -9,110 +9,159 @@ const util = require('./util');
const { rollup } = require('rollup');
const babel = require('rollup-plugin-babel');
const minify = require('rollup-plugin-babel-minify');
// Set variables for paths
const MODULE_NAME = '_30s';
const SNIPPETS_PATH = './snippets';
const SNIPPETS_ARCHIVE_PATH = './snippets_archive';
const IMPORTS = './imports.js';
const TEST_PACKAGE = './test/_30s.js';
const MODULE_NAME = '_30s';
const DIST = './dist';
// Regex for selecting code blocks
const codeRE = /```\s*js([\s\S]*?)```/;
// Read snippets, build packages
(async () => {
// Start the timer of the script
const DIST_PATH = './dist';
const ROLLUP_INPUT_FILE = './imports.temp.js';
const TEST_MODULE_FILE = './test/_30s.js';
const CODE_RE = /```\s*js([\s\S]*?)```/;
/**
* Returns the raw markdown string.
*/
function getRawSnippetString(snippetPath, snippet) {
return fs.readFileSync(path.join(snippetPath, snippet), 'utf8');
}
/**
* Returns the JavaScript code from the raw markdown string.
*/
function getCode(rawSnippetString) {
return rawSnippetString.match(CODE_RE)[1].replace('\n', '');
}
/**
* Builds the UMD + ESM files to the ./dist directory.
*/
async function doRollup() {
// Plugins
const es5 = babel({ presets: ['@babel/preset-env'] });
const min = minify({ comments: false });
const output = format => file => ({
format,
file,
name: MODULE_NAME
});
const umd = output('umd');
const esm = output('es');
const bundle = await rollup({ input: ROLLUP_INPUT_FILE });
const bundleES5 = await rollup({ input: ROLLUP_INPUT_FILE, plugins: [es5] });
const bundleES5Min = await rollup({
input: ROLLUP_INPUT_FILE,
plugins: [es5, min]
});
const baseName = `${DIST_PATH}/${MODULE_NAME}`;
// UMD ES2018
await bundle.write(umd(`${baseName}.js`));
// ESM ES2018
await bundle.write(esm(`${baseName}.esm.js`));
// UMD ES5
await bundleES5.write(umd(`${baseName}.es5.js`));
// UMD ES5 min
await bundleES5Min.write(umd(`${baseName}.es5.min.js`));
}
/**
* Starts the build process.
*/
async function build() {
console.time('Packager');
let requires = [];
let esmExportString = '';
let cjsExportString = '';
try {
const tagDatabase = fs.readFileSync('tag_database', 'utf8');
const nodeSnippets = tagDatabase.split('\n').filter(v => v.search(/:.*node/g) !== -1).map(v => v.slice(0,v.indexOf(':')));
if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
fs.writeFileSync(ROLLUP_INPUT_FILE, '');
fs.writeFileSync(TEST_MODULE_FILE, '');
// All the snippets that are Node.js-based and will break in a browser
// environment
const nodeSnippets = fs
.readFileSync('tag_database', 'utf8')
.split('\n')
.filter(v => v.search(/:.*node/g) !== -1)
.map(v => v.slice(0, v.indexOf(':')));
const snippets = fs.readdirSync(SNIPPETS_PATH);
const snippetExports = `module.exports = {${snippets.map(v => v.replace('.md', '')).join(',')}}`;
let requires = [];
let importData = '';
const archivedSnippets = fs.readdirSync(SNIPPETS_ARCHIVE_PATH).filter(v => v !== 'README.md');
const testExports = `module.exports = {${[...snippets,...archivedSnippets].map(v => v.replace('.md', '')).join(',')}}`;
// Create `temp` and `dist` folders if they don't already exist.
if (!fs.existsSync(DIST)) fs.mkdirSync(DIST);
// Write `imports.js`
fs.writeFileSync(IMPORTS, '');
fs.writeFileSync(TEST_PACKAGE, '');
const archivedSnippets = fs
.readdirSync(SNIPPETS_ARCHIVE_PATH)
.filter(v => v !== 'README.md');
snippets.forEach(snippet => {
const snippetData = fs.readFileSync(path.join(SNIPPETS_PATH, snippet), 'utf8');
const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
const snippetName = snippet.replace('.md', '');
let code = snippetData.match(codeRE)[1].replace('\n', '');
let code = getCode(rawSnippetString);
if (nodeSnippets.includes(snippetName)) {
requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
code = code.replace(/const.*=.*require\(([^\)]*)\);/g,'');
code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
}
importData += code;
esmExportString += `export ${code}`;
cjsExportString += code;
});
// Write the data to the imports file
requires = [...new Set(requires.filter(Boolean).map(v => v[0].replace('require(', 'typeof require !== "undefined" && require(')))].join('\n');
fs.writeFileSync(IMPORTS, `${requires}\n\n${importData}\n\n${snippetExports}`);
archivedSnippets.forEach(snippet => {
const snippetData = fs.readFileSync(path.join(SNIPPETS_ARCHIVE_PATH, snippet), 'utf8');
let code = snippetData.match(codeRE)[1].replace('\n', '');
importData += code;
const rawSnippetString = getRawSnippetString(
SNIPPETS_ARCHIVE_PATH,
snippet
);
cjsExportString += getCode(rawSnippetString);
});
fs.writeFileSync(TEST_PACKAGE, `${requires}\n\n${importData}\n\n${testExports}`);
requires = [
...new Set(
requires
.filter(Boolean)
.map(v =>
v[0].replace(
'require(',
'typeof require !== "undefined" && require('
)
)
)
].join('\n');
fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);
const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
.map(v => v.replace('.md', ''))
.join(',')}}`;
fs.writeFileSync(
TEST_MODULE_FILE,
`${requires}\n\n${cjsExportString}\n\n${testExports}`
);
// Check Travis builds - Will skip builds on Travis if not CRON/API
if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
fs.unlink(IMPORTS);
fs.unlink(ROLLUP_INPUT_FILE);
console.log(
`${chalk.green('NOBUILD')} Module build terminated, not a cron job or a custom build!`
`${chalk.green(
'NOBUILD'
)} Module build terminated, not a cron job or a custom build!`
);
console.timeEnd('Packager');
process.exit(0);
}
// Write to the proper files and start the `rollup` script
const es5 = babel({
presets: ['@babel/preset-env']
});
const min = minify({ comments: false });
const bundle = await rollup({ input: IMPORTS });
// UMD ES2018
await bundle.write({
file: `${DIST}/${MODULE_NAME}.js`,
name: MODULE_NAME,
format: 'umd'
});
// ESM ES2018
await bundle.write({
file: `${DIST}/${MODULE_NAME}.esm.js`,
name: MODULE_NAME,
format: 'es'
});
// UMD ES5
const bundleES5 = await rollup({ input: IMPORTS, plugins: [es5] });
await bundleES5.write({
file: `${DIST}/${MODULE_NAME}.es5.js`,
name: MODULE_NAME,
format: 'umd'
});
// UMD ES5 min
const bundleES5Min = await rollup({
input: IMPORTS,
plugins: [es5, min]
});
await bundleES5Min.write({
file: `${DIST}/${MODULE_NAME}.es5.min.js`,
name: MODULE_NAME,
format: 'umd'
});
// Clean up temporary data
fs.unlink(IMPORTS);
// Log a success message
await doRollup();
// Clean up the temporary input file Rollup used for building the module
fs.unlink(ROLLUP_INPUT_FILE);
console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
// Log the time taken
console.timeEnd('Packager');
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
process.exit(1);
}
})();
}
build();

View File

@ -38,8 +38,7 @@ try {
output += `${snippet[0].slice(0, -3)}:${tagDbData[snippet[0].slice(0, -3)]
.join(',')
.trim()}\n`;
}
else {
} else {
output += `${snippet[0].slice(0, -3)}:uncategorized\n`;
missingTags++;
console.log(`${chalk.yellow('Tagged uncategorized:')} ${snippet[0].slice(0, -3)}`);
@ -47,8 +46,7 @@ try {
}
// Write to tag_database
fs.writeFileSync('tag_database', output);
}
catch (err) {
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During tag_database generation: ${err}`);
process.exit(1);

View File

@ -9,10 +9,6 @@ const fs = require('fs-extra'),
const childProcess = require('child_process');
const chalk = require('chalk');
const util = require('./util');
if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
console.log(`${chalk.green('NOBUILD')} Testing terminated, not a cron job or a custom build!`);
process.exit(0);
}
// Declare paths
const SNIPPETS_PATH = './snippets';
const SNIPPETS_ARCHIVE_PATH = './snippets_archive';
@ -28,7 +24,7 @@ try {
const orphanedTests = [...definedTests.filter(v => ![...snippets, ...archivedSnippets].includes(v))];
orphanedTests.forEach(snippet => {
console.log(`${chalk.yellow('WARNING!')} Orphaned test: ${snippet}`);
})
});
// Create files for undefined tests
undefinedTests.forEach(snippet => {
const exportTest = [
@ -41,11 +37,15 @@ try {
fs.writeFileSync(path.join(TEST_PATH, `${snippet}.test.js`), exportTest);
});
// Run tests
fs.writeFileSync(path.join(TEST_PATH, 'testlog'), `Test log for: ${new Date().toString()}\n`);
childProcess.execSync('npm test');
if (util.isTravisCI()) {
process.exit(0);
}
else {
childProcess.execSync('npm test');
}
console.log(`${chalk.green('SUCCESS!')} All tests ran successfully!`);
} catch (err) {
console.log(`${chalk.red('ERROR!')} During test runs: ${err}`);
process.exit(1);
}
console.timeEnd('Tester');
console.timeEnd('Tester');

View File

@ -32,8 +32,7 @@ const getFilesInDir = (directoryPath, withPath, exclude = null) => {
}, []);
}
return directoryFilenames;
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`);
process.exit(1);
}
@ -47,8 +46,7 @@ const readSnippets = snippetsPath => {
try {
for (let snippet of snippetFilenames)
snippets[snippet] = fs.readFileSync(path.join(snippetsPath, snippet), 'utf8');
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During snippet loading: ${err}`);
process.exit(1);
}
@ -71,8 +69,7 @@ const readTags = () => {
return data;
})
);
}
catch (err) {
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During tag database loading: ${err}`);
process.exit(1);
@ -131,9 +128,9 @@ const getCodeBlocks = str => {
results = results.map(v => v.replace(/```js([\s\S]*?)```/g, '$1').trim());
return {
es6: results[0],
es5: babel.transformSync(results[0], { presets: ['@babel/preset-env'] }).code.replace('"use strict";\n\n',''),
es5: babel.transformSync(results[0], { presets: ['@babel/preset-env'] }).code.replace('"use strict";\n\n', ''),
example: results[1]
}
};
};
// Gets the textual content for a snippet file.
const getTextualContent = str => {

View File

@ -11,10 +11,10 @@ let snippetsData = require('../snippet_data/snippets.json');
const OUTPUT_PATH = './vscode_snippets';
console.time('VSCoder');
// Read and format data
let vscodeData = snippetsData.data.filter(v => !v.meta.archived ).reduce((acc,v) => {
let vscodeData = snippetsData.data.filter(v => !v.meta.archived ).reduce((acc, v) => {
acc[v.id] = {
prefix: `30s_${v.id}`,
body: v.attributes.codeBlocks.es6.replace(/\r/g,'').split('\n'),
body: v.attributes.codeBlocks.es6.replace(/\r/g, '').split('\n'),
description: v.attributes.text.slice(0, v.attributes.text.indexOf('\r\n\r\n'))
};
return acc;
@ -30,4 +30,4 @@ console.log(
'SUCCESS!'
)} vscode_snippets/snippets.json file generated!`
);
console.timeEnd('VSCoder');
console.timeEnd('VSCoder');

View File

@ -109,8 +109,7 @@ sass.render(
if (!err2) console.log(`${chalk.green('SUCCESS!')} style.css file generated!`);
else console.log(`${chalk.red('ERROR!')} During style.css file generation: ${err}`);
});
}
else
} else
console.log(`${chalk.red('ERROR!')} During style.css file generation: ${err}`);
}
@ -148,8 +147,7 @@ try {
'static-page-start.html',
'static-page-end.html'
].map(filename => fs.readFileSync(path.join(staticPartsPath, filename), 'utf8'));
}
catch (err) {
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During static part loading: ${err}`);
process.exit(1);
@ -234,14 +232,13 @@ try {
`${chalk.green('SUCCESS!')} ${page.tag === 'array' ? 'index' : page.tag}.html file generated!`
);
});
}
catch (err) {
} catch (err) {
// Handle errors (hopefully not!)
console.log(`${chalk.red('ERROR!')} During category page generation: ${err}`);
process.exit(1);
}
const generateMenuForStaticPage = (staticPart) => {
const generateMenuForStaticPage = staticPart => {
let taggedData = util.prepTaggedData(tagDbData);
// Add the start static part
let htmlCode;
@ -258,7 +255,7 @@ const generateMenuForStaticPage = (staticPart) => {
htmlCode += md
.render(
`[${taggedSnippet[0]}](./${
tag === 'array' ? 'index' : tag
tag === 'array' ? 'index' : tag
}#${taggedSnippet[0].toLowerCase()})\n`
)
.replace(/<p>/g, '')
@ -268,7 +265,7 @@ const generateMenuForStaticPage = (staticPart) => {
htmlCode += '</ul>\n';
}
return staticPart.replace('$nav-menu-data', htmlCode);
}
};
const staticPageStartGenerator = (staticPart, heading, description) => {
let taggedData = util.prepTaggedData(tagDbData);
@ -350,8 +347,7 @@ try {
fs.writeFileSync(path.join(docsPath, 'archive.html'), minifiedArchivedOutput);
console.log(`${chalk.green('SUCCESS!')} archive.html file generated!`);
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During archive.html generation: ${err}`);
process.exit(1);
}
@ -384,8 +380,7 @@ try {
const minifiedGlossaryOutput = minifyHTML(glossaryOutput);
fs.writeFileSync(path.join(docsPath, 'glossary.html'), minifiedGlossaryOutput);
console.log(`${chalk.green('SUCCESS!')} glossary.html file generated!`);
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During glossary.html generation: ${err}`);
process.exit(1);
}
@ -396,12 +391,10 @@ staticFiles.forEach(f => {
if(f !== 'array.html') {
let fileData = fs.readFileSync(path.join(staticPartsPath, f), 'utf8');
fs.writeFileSync(path.join(docsPath, f), generateMenuForStaticPage(fileData));
}
else
} else
fs.copyFileSync(path.join(staticPartsPath, f), path.join(docsPath, f));
console.log(`${chalk.green('SUCCESS!')} ${f} file copied!`);
}
catch (err) {
} catch (err) {
console.log(`${chalk.red('ERROR!')} During ${f} copying: ${err}`);
process.exit(1);
}

View File

@ -1664,7 +1664,7 @@
"archived": false
},
"meta": {
"hash": "8b7b70809f93fd9392315a5c63aa4cbbf9b45eb1165a7d44db314186d407816b"
"hash": "40558410bed6e9e2866362dc86898fd28a97073f798d8dd5c566eea2ccec2f8f"
}
},
{
@ -4414,7 +4414,7 @@
"archived": false
},
"meta": {
"hash": "c7a62b55b5a90661bf3f9c956f075906439a50151a3aee4023ad8fe878cae2e6"
"hash": "2fd449a2a993bdbc2b93d185ef09aea72af7845152de46d6050db82efe912130"
}
},
{
@ -5205,7 +5205,7 @@
"archived": true
},
"meta": {
"hash": "f5cb5c0acd7e7bca28ac3a7e2c0292db8f72b2e0598dd0b84270d3eb1cc72c8b"
"hash": "7af37e0984b5c8bd78d6b224cdc155f8c2bf687e38b5cfee27f32c7c29dcddf5"
}
},
{

View File

@ -2443,8 +2443,8 @@
"fileName": "hide.md",
"text": "Hides all the elements specified.\n\nUse `NodeList.prototype.forEach()` to apply `display: none` to each element specified.",
"codeBlocks": {
"es6": "const hide = els => els.forEach(e => (e.style.display = 'none'));",
"es5": "var hide = function hide(els) {\n return els.forEach(function (e) {\n return e.style.display = 'none';\n });\n};",
"es6": "const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));",
"es5": "var hide = function hide() {\n for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) {\n el[_key] = arguments[_key];\n }\n\n return el.concat().forEach(function (e) {\n return e.style.display = 'none';\n });\n};",
"example": "hide(document.querySelectorAll('img')); // Hides all <img> elements on the page"
},
"tags": [
@ -2455,7 +2455,7 @@
},
"meta": {
"archived": false,
"hash": "8b7b70809f93fd9392315a5c63aa4cbbf9b45eb1165a7d44db314186d407816b"
"hash": "40558410bed6e9e2866362dc86898fd28a97073f798d8dd5c566eea2ccec2f8f"
}
},
{
@ -6491,7 +6491,7 @@
"codeBlocks": {
"es6": "const toHash = (object, key) =>\n Array.prototype.reduce.call(\n object,\n (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc),\n {}\n );",
"es5": "var toHash = function toHash(object, key) {\n return Array.prototype.reduce.call(object, function (acc, data, index) {\n return acc[!key ? index : data[key]] = data, acc;\n }, {});\n};",
"example": "toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 }\ntoHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }\n// A more in depth example:\nlet users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];\nlet managers = [{ manager: 1, employees: [2, 3] }];\n// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.\nmanagers.forEach(\n manager =>\n (manager.employees = manager.employees.map(function(id) {\n return this[id];\n }, toHash(users, 'id')))\n);\nmanagers; // [ { manager:1, employees: [ { id: 2, first: \"Joe\" }, { id: 3, first: \"Moe\" } ] } ]"
"example": "toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }\ntoHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }\n// A more in depth example:\nlet users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];\nlet managers = [{ manager: 1, employees: [2, 3] }];\n// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.\nmanagers.forEach(\n manager =>\n (manager.employees = manager.employees.map(function(id) {\n return this[id];\n }, toHash(users, 'id')))\n);\nmanagers; // [ { manager:1, employees: [ { id: 2, first: \"Joe\" }, { id: 3, first: \"Moe\" } ] } ]"
},
"tags": [
"array",
@ -6500,7 +6500,7 @@
},
"meta": {
"archived": false,
"hash": "c7a62b55b5a90661bf3f9c956f075906439a50151a3aee4023ad8fe878cae2e6"
"hash": "2fd449a2a993bdbc2b93d185ef09aea72af7845152de46d6050db82efe912130"
}
},
{
@ -7704,7 +7704,7 @@
},
"meta": {
"archived": true,
"hash": "f5cb5c0acd7e7bca28ac3a7e2c0292db8f72b2e0598dd0b84270d3eb1cc72c8b"
"hash": "7af37e0984b5c8bd78d6b224cdc155f8c2bf687e38b5cfee27f32c7c29dcddf5"
}
},
{

View File

@ -5,7 +5,7 @@ Hides all the elements specified.
Use `NodeList.prototype.forEach()` to apply `display: none` to each element specified.
```js
const hide = els => els.forEach(e => (e.style.display = 'none'));
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
```
```js

View File

@ -14,7 +14,7 @@ const toHash = (object, key) =>
```
```js
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 }
toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }
toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }
// A more in depth example:
let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];

View File

@ -5,5 +5,5 @@ test('JSONToDate is a Function', () => {
expect(JSONToDate).toBeInstanceOf(Function);
});
test('JSONToDate returns the correct date string', () => {
expect(JSONToDate(/Date(1489525200000)/)).toBe("14/3/2017");
expect(JSONToDate(/Date(1489525200000)/)).toBe('14/3/2017');
});

View File

@ -482,7 +482,7 @@ const hexToRGB = hex => {
')'
);
};
const hide = els => els.forEach(e => (e.style.display = 'none'));
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
const httpGet = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('GET', url, true);

View File

@ -6,7 +6,7 @@ test('bindAll is a Function', () => {
});
var view = {
label: 'docs',
click: function() {
click() {
return 'clicked ' + this.label;
}
};

View File

@ -6,7 +6,7 @@ test('bindKey is a Function', () => {
});
const freddy = {
user: 'fred',
greet: function(greeting, punctuation) {
greet(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
}
};

View File

@ -4,3 +4,6 @@ const {bottomVisible} = require('./_30s.js');
test('bottomVisible is a Function', () => {
expect(bottomVisible).toBeInstanceOf(Function);
});
test('bottomVisible returns a boolean', () => {
expect(typeof bottomVisible()).toBe('boolean');
});

View File

@ -1,4 +1,5 @@
const expect = require('expect');
const { byteSize } = require('./_30s.js');
const Blob = class {
constructor(s) {
return {
@ -6,7 +7,6 @@ const Blob = class {
};
}
};
const byteSize = str => new Blob([str]).size;
test('byteSize is a Function', () => {
expect(byteSize).toBeInstanceOf(Function);

View File

@ -6,21 +6,21 @@ test('celsiusToFahrenheit is a Function', () => {
});
test('0 Celsius is 32 Fahrenheit', () => {
expect(celsiusToFahrenheit(0)).toBe(32)
})
expect(celsiusToFahrenheit(0)).toBe(32);
});
test('100 Celsius is 212 Fahrenheit', () => {
expect(celsiusToFahrenheit(100)).toBe(212)
})
expect(celsiusToFahrenheit(100)).toBe(212);
});
test('-50 Celsius is -58 Fahrenheit', () => {
expect(celsiusToFahrenheit(-50)).toBe(-58)
})
expect(celsiusToFahrenheit(-50)).toBe(-58);
});
test('1000 Celsius is 1832 Fahrenheit', () => {
expect(celsiusToFahrenheit(1000)).toBe(1832)
})
expect(celsiusToFahrenheit(1000)).toBe(1832);
});
test('Not a number value is NaN', () => {
expect(celsiusToFahrenheit("Durr")).toBe(NaN)
})
expect(celsiusToFahrenheit('Durr')).toBe(NaN);
});

View File

@ -4,3 +4,28 @@ const {copyToClipboard} = require('./_30s.js');
test('copyToClipboard is a Function', () => {
expect(copyToClipboard).toBeInstanceOf(Function);
});
test('copyToClipboard does not throw errors', () => {
document.getSelection = function() {
return {
rangeCount: 0,
removeAllRanges() { return; },
addRange(x) { return x; }
};
};
document.execCommand = function(x) { return x; };
expect(copyToClipboard('hi')).toBe(undefined);
});
test('copyToClipboard does not throw errors', () => {
document.getSelection = function() {
return {
rangeCount: 1,
getRangeAt(x) { return x + 1; },
removeAllRanges() { return; },
addRange(x) { return x; }
};
};
document.execCommand = function(x) { return x; };
expect(copyToClipboard('hi')).toBe(undefined);
});

View File

@ -4,3 +4,11 @@ const {counter} = require('./_30s.js');
test('counter is a Function', () => {
expect(counter).toBeInstanceOf(Function);
});
test('counter does not throw errors', () => {
expect(() => {
document.body.appendChild(document.createElement('div'));
counter('div', 1, 1000, 5, 2000);
counter('div', 1000, 1, 5, 2000);
counter('div', 1, 1000);
}).not.toThrow(TypeError);
});

View File

@ -4,3 +4,14 @@ const {createEventHub} = require('./_30s.js');
test('createEventHub is a Function', () => {
expect(createEventHub).toBeInstanceOf(Function);
});
test('createEventHub returns an object', () => {
let hub = createEventHub();
expect(typeof hub).toBe('object');
expect(typeof hub.hub).toBe('object');
expect(hub.emit).toBeInstanceOf(Function);
expect(hub.on).toBeInstanceOf(Function);
expect(hub.off).toBeInstanceOf(Function);
expect(hub.emit()).toBe(undefined);
expect(hub.on()).toBe(undefined);
expect(hub.off()).toBe(undefined);
});

View File

@ -4,3 +4,13 @@ const {elementContains} = require('./_30s.js');
test('elementContains is a Function', () => {
expect(elementContains).toBeInstanceOf(Function);
});
test('elementContains returns true', () => {
let p = document.createElement('div');
let c = p.appendChild(document.createElement('div'));
expect(elementContains(p, c)).toBeTruthy();
});
test('elementContains returns false', () => {
let p = document.createElement('div');
let c = document.createElement('div');
expect(elementContains(p, c)).toBeFalsy();
});

View File

@ -4,3 +4,11 @@ const {elementIsVisibleInViewport} = require('./_30s.js');
test('elementIsVisibleInViewport is a Function', () => {
expect(elementIsVisibleInViewport).toBeInstanceOf(Function);
});
test('elementIsVisibleInViewport returns a boolean', () => {
let el = document.createElement('div');
expect(typeof elementIsVisibleInViewport(el)).toBe('boolean');
});
test('elementIsVisibleInViewport returns a boolean', () => {
let el = document.createElement('div');
expect(typeof elementIsVisibleInViewport(el, true)).toBe('boolean');
});

View File

@ -6,21 +6,21 @@ test('fahrenheitToCelsius is a Function', () => {
});
test('32 Fahrenheit is 0 Celsius', () => {
expect(fahrenheitToCelsius(32)).toBe(0)
})
expect(fahrenheitToCelsius(32)).toBe(0);
});
test('212 Fahrenheit is 100 Celsius', () => {
expect(fahrenheitToCelsius(212)).toBe(100)
})
expect(fahrenheitToCelsius(212)).toBe(100);
});
test('150 Fahrenheit is 65.55555555555556 Celsius', () => {
expect(fahrenheitToCelsius(150)).toBe(65.55555555555556)
})
expect(fahrenheitToCelsius(150)).toBe(65.55555555555556);
});
test('1000 Fahrenheit is 537.7777777777778', () => {
expect(fahrenheitToCelsius(1000)).toBe(537.7777777777778)
})
expect(fahrenheitToCelsius(1000)).toBe(537.7777777777778);
});
test('Not a number value is NaN', () => {
expect(fahrenheitToCelsius("Durr")).toBe(NaN)
})
expect(fahrenheitToCelsius('Durr')).toBe(NaN);
});

View File

@ -7,4 +7,4 @@ test('getColonTimeFromDate is a Function', () => {
test('Gets the time in the proper format.', () => {
let date = new Date();
expect(getColonTimeFromDate(date)).toEqual(date.toTimeString().slice(0, 8));
});
});

View File

@ -1,18 +1,18 @@
const expect = require("expect");
const {getImages} = require("./_30s.js");
const jsdom = require("jsdom");
const expect = require('expect');
const {getImages} = require('./_30s.js');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const TEST_HTML = new JSDOM("<!DOCTYPE html><p>Hello world</p><img src=\"https://upload.wikimedia.org/wikipedia/en/1/12/Yellow_Smiley_Face.png\"></img>").window.document;
const TEST_HTML = new JSDOM('<!DOCTYPE html><p>Hello world</p><img src="https://upload.wikimedia.org/wikipedia/en/1/12/Yellow_Smiley_Face.png"></img>').window.document;
test("getImages is a Function", () => {
expect(getImages).toBeInstanceOf(Function);
test('getImages is a Function', () => {
expect(getImages).toBeInstanceOf(Function);
});
test("getImages returns an Array", () => {
expect(getImages(TEST_HTML)).toBeInstanceOf(Array);
test('getImages returns an Array', () => {
expect(getImages(TEST_HTML)).toBeInstanceOf(Array);
});
test("getImages removes duplicates from images Array", () => {
expect(getImages(TEST_HTML, false).length).toBeLessThanOrEqual(getImages(TEST_HTML, true).length);
expect(getImages(TEST_HTML, true)).toEqual(expect.arrayContaining(getImages(TEST_HTML, false)));
test('getImages removes duplicates from images Array', () => {
expect(getImages(TEST_HTML, false).length).toBeLessThanOrEqual(getImages(TEST_HTML, true).length);
expect(getImages(TEST_HTML, true)).toEqual(expect.arrayContaining(getImages(TEST_HTML, false)));
});

View File

@ -4,3 +4,14 @@ const {getScrollPosition} = require('./_30s.js');
test('getScrollPosition is a Function', () => {
expect(getScrollPosition).toBeInstanceOf(Function);
});
test('getScrollPosition returns an object with x and y values', () => {
let scrollPos = getScrollPosition();
expect(typeof scrollPos.x).toBe('number');
expect(typeof scrollPos.y).toBe('number');
});
test('getScrollPosition returns an object with x and y values', () => {
let el = document.createElement('div');
let scrollPos = getScrollPosition(el);
expect(typeof scrollPos.x).toBe('number');
expect(typeof scrollPos.y).toBe('number');
});

View File

@ -4,3 +4,8 @@ const {getStyle} = require('./_30s.js');
test('getStyle is a Function', () => {
expect(getStyle).toBeInstanceOf(Function);
});
test('getStyle returns the proper value', () => {
let el = document.createElement('div');
el.setAttribute('style', 'font-size: 20px;');
expect(getStyle(el, 'font-size')).toBe('20px');
});

View File

@ -4,3 +4,8 @@ const {hasClass} = require('./_30s.js');
test('hasClass is a Function', () => {
expect(hasClass).toBeInstanceOf(Function);
});
test('hasClass returns the proper value', () => {
let el = document.createElement('div');
el.classList.add('myClass');
expect(hasClass(el, 'myClass')).toBeTruthy();
});

View File

@ -4,3 +4,9 @@ const {hide} = require('./_30s.js');
test('hide is a Function', () => {
expect(hide).toBeInstanceOf(Function);
});
test('hide hides an element', () => {
let el = document.createElement('div');
el.setAttribute('style', 'display: block;');
hide(el);
expect(el.style.display).toBe('none');
});

View File

@ -4,3 +4,9 @@ const {httpDelete} = require('./_30s.js');
test('httpDelete is a Function', () => {
expect(httpDelete).toBeInstanceOf(Function);
});
test('httpDelete does not throw errors', () => {
expect(() => {
httpDelete('http://localhost', x => x, console.log);
httpDelete('http://localhost', x => x);
}).not.toThrow(TypeError);
});

View File

@ -4,3 +4,9 @@ const {httpGet} = require('./_30s.js');
test('httpGet is a Function', () => {
expect(httpGet).toBeInstanceOf(Function);
});
test('httpGet does not throw errors', () => {
expect(() => {
httpGet('http://localhost', x => x, console.log);
httpGet('http://localhost', x => x);
}).not.toThrow(TypeError);
});

View File

@ -4,3 +4,9 @@ const {httpPost} = require('./_30s.js');
test('httpPost is a Function', () => {
expect(httpPost).toBeInstanceOf(Function);
});
test('httpPost does not throw errors', () => {
expect(() => {
httpPost('http://localhost', x => x, console.log);
httpPost('http://localhost', x => x);
}).not.toThrow(TypeError);
});

View File

@ -4,3 +4,9 @@ const {httpPut} = require('./_30s.js');
test('httpPut is a Function', () => {
expect(httpPut).toBeInstanceOf(Function);
});
test('httpPut does not throw errors', () => {
expect(() => {
httpPut('http://localhost', x => x, console.log);
httpPut('http://localhost', x => x);
}).not.toThrow(TypeError);
});

View File

@ -8,5 +8,5 @@ test('Initializes a n-D array with given data', () => {
expect(initializeNDArray(1, 3)).toEqual([1, 1, 1]);
});
test('Initializes a n-D array with given data', () => {
expect(initializeNDArray(5, 2, 2, 2)).toEqual([[[5, 5], [5, 5]],[[5, 5], [5, 5]]]);
expect(initializeNDArray(5, 2, 2, 2)).toEqual([[[5, 5], [5, 5]], [[5, 5], [5, 5]]]);
});

View File

@ -5,7 +5,7 @@ test('insertAfter is a Function', () => {
expect(insertAfter).toBeInstanceOf(Function);
});
let e = document.createElement('div');
e.setAttribute("id", "test");
e.setAttribute('id', 'test');
test('Does not throw error if the element exists', () => {
expect(() => {
insertAfter(e, '<span>test</span>');

View File

@ -5,7 +5,7 @@ test('insertBefore is a Function', () => {
expect(insertBefore).toBeInstanceOf(Function);
});
let e = document.createElement('div');
e.setAttribute("id", "test");
e.setAttribute('id', 'test');
test('Does not throw error if the element exists', () => {
expect(() => {
insertBefore(e, '<span>test</span>');

View File

@ -7,3 +7,6 @@ test('isPrime is a Function', () => {
test('passed number is a prime', () => {
expect(isPrime(11)).toBeTruthy();
});
test('passed number is not a prime', () => {
expect(isPrime(10)).toBeFalsy();
});

View File

@ -7,7 +7,7 @@ test('isPromiseLike is a Function', () => {
test('Returns true for a promise-like object', () => {
expect(
isPromiseLike({
then: function() {
then() {
return '';
}
})

View File

@ -4,11 +4,12 @@ const {isTravisCI} = require('./_30s.js');
test('isTravisCI is a Function', () => {
expect(isTravisCI).toBeInstanceOf(Function);
});
if (isTravisCI())
if (isTravisCI()) {
test('Running on Travis, correctly evaluates', () => {
expect(isTravisCI()).toBeTruthy();
});
else
} else {
test('Not running on Travis, correctly evaluates', () => {
expect(isTravisCI()).toBeFalsy();
});
}

View File

@ -12,6 +12,9 @@ test('Function works properly', () => {
test('Function works properly', () => {
expect(square(3)).toBe(9);
});
test('Function works properly, cache stores values (coverage)', () => {
expect(square(3)).toBe(9);
});
test('Cache stores values', () => {
expect(Array.from(square.cache)).toEqual([[2, 4], [3, 9]]);
});

View File

@ -4,3 +4,6 @@ const {nodeListToArray} = require('./_30s.js');
test('nodeListToArray is a Function', () => {
expect(nodeListToArray).toBeInstanceOf(Function);
});
test('nodeListToArray returns an array of proper length', () => {
expect(nodeListToArray(document.childNodes).length).toBe(2);
});

View File

@ -4,3 +4,31 @@ const {off} = require('./_30s.js');
test('off is a Function', () => {
expect(off).toBeInstanceOf(Function);
});
test('off removes an event listener', () => {
let el = document.createElement('div');
let val = false;
const fn = () => val = true;
el.addEventListener('click', fn);
off(el, 'click', fn);
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
el.dispatchEvent(clickEvent);
expect(val).toBeFalsy();
});
test('off removes an event listener', () => {
let el = document.createElement('div');
let val = false;
const fn = () => val = true;
el.addEventListener('click', fn);
off(el, 'click', fn, {});
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
el.dispatchEvent(clickEvent);
expect(val).toBeFalsy();
});

View File

@ -4,3 +4,30 @@ const {on} = require('./_30s.js');
test('on is a Function', () => {
expect(on).toBeInstanceOf(Function);
});
test('on creates an event listener', () => {
let el = document.createElement('div');
let val = false;
const fn = () => val = true;
on(el, 'click', fn);
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
el.dispatchEvent(clickEvent);
expect(val).toBeTruthy();
});
test('on creates an event listener', () => {
let el = document.createElement('div');
document.body.appendChild(el);
let val = false;
const fn = () => val = true;
on(document.body, 'click', fn, { target: 'div' });
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
el.dispatchEvent(clickEvent);
expect(val).toBeTruthy();
});

View File

@ -4,6 +4,11 @@ const {once} = require('./_30s.js');
test('once is a Function', () => {
expect(once).toBeInstanceOf(Function);
});
test('once is a Function', () => {
test('once returns Function', () => {
expect(typeof once(x => 10)).toBe('function');
});
test('once returns the result only once', () => {
let onced = once(x => x);
expect(onced(10)).toBe(10);
expect(onced(10)).toBe(undefined);
});

View File

@ -14,3 +14,6 @@ test('Generates all permutations of an array', () => {
[5, 33, 1]
]);
});
test('Generates all permutations of an array', () => {
expect(permutations([1])).toEqual([1]);
});

View File

@ -13,9 +13,12 @@ test('Produces the singular of the word', () => {
test('Produces the plural of the word', () => {
expect(pluralize(2, 'apple')).toBe('apples');
});
test('Prodices the defined plural of the word', () => {
test('Produces the defined plural of the word', () => {
expect(pluralize(2, 'person', 'people')).toBe('people');
});
test('Produces the defined plural of the word', () => {
expect(pluralize(1, 'person', 'people')).toBe('person');
});
const PLURALS = {
person: 'people',
radius: 'radii'

View File

@ -13,3 +13,9 @@ test('Converts a number in bytes to a human-readable string.', () => {
test('Converts a number in bytes to a human-readable string.', () => {
expect(prettyBytes(123456789, 3, false)).toBe('123MB');
});
test('Converts a number in bytes to a human-readable string.', () => {
expect(prettyBytes(0, 3, false)).toBe('0B');
});
test('Converts a number in bytes to a human-readable string.', () => {
expect(prettyBytes(0, 3, true)).toBe('0 B');
});

View File

@ -1,21 +1,21 @@
const expect = require("expect");
const {shank} = require("./_30s.js");
const expect = require('expect');
const {shank} = require('./_30s.js');
test("shank is a Function", () => {
test('shank is a Function', () => {
expect(shank).toBeInstanceOf(Function);
});
const names = ['alpha', 'bravo', 'charlie'];
test("Returns an array with the added elements.", () => {
test('Returns an array with the added elements.', () => {
expect(shank(names, 1, 0, 'delta')).toEqual(['alpha', 'delta', 'bravo', 'charlie']);
});
test("Returns an array with the removed elements.", () => {
test('Returns an array with the removed elements.', () => {
expect(shank(names, 1, 1)).toEqual(['alpha', 'charlie']);
});
test("Does not mutate the original array", () => {
test('Does not mutate the original array', () => {
shank(names, 1, 0, 'delta');
expect(names).toEqual(['alpha', 'bravo', 'charlie']);
});

View File

@ -4,3 +4,9 @@ const {show} = require('./_30s.js');
test('show is a Function', () => {
expect(show).toBeInstanceOf(Function);
});
test('show shows an element', () => {
let el = document.createElement('div');
el.setAttribute('style', 'display: none;');
show(el);
expect(el.style.display).not.toBe('none');
});

View File

@ -10,3 +10,6 @@ test('Returns the lowest index at which value should be inserted into array in o
test('Returns the lowest index at which value should be inserted into array in order to maintain its sort order.', () => {
expect(sortedIndex([30, 50], 40)).toBe(1);
});
test('Returns the lowest index at which value should be inserted into array in order to maintain its sort order.', () => {
expect(sortedIndex([30, 50], 60)).toBe(2);
});

View File

@ -7,3 +7,9 @@ test('sortedIndexBy is a Function', () => {
test('Returns the lowest index to insert the element without messing up the list order', () => {
expect(sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x)).toBe(0);
});
test('Returns the lowest index to insert the element without messing up the list order', () => {
expect(sortedIndexBy([{ x: 5 }, { x: 4 }], { x: 4 }, o => o.x)).toBe(1);
});
test('Returns the lowest index to insert the element without messing up the list order', () => {
expect(sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 6 }, o => o.x)).toBe(2);
});

View File

@ -7,3 +7,9 @@ test('sortedLastIndex is a Function', () => {
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndex([10, 20, 30, 30, 40], 30)).toBe(4);
});
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndex([40, 30, 10], 20)).toBe(2);
});
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndex([10, 20, 30, 30, 40], 5)).toBe(0);
});

View File

@ -7,3 +7,9 @@ test('sortedLastIndexBy is a Function', () => {
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x)).toBe(1);
});
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndexBy([{ x: 5 }, { x: 4 }], { x: 5 }, o => o.x)).toBe(1);
});
test('Returns the highest index to insert the element without messing up the list order', () => {
expect(sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 3 }, o => o.x)).toBe(0);
});

View File

@ -4,3 +4,6 @@ const {squareSum} = require('./_30s.js');
test('squareSum is a Function', () => {
expect(squareSum).toBeInstanceOf(Function);
});
test('squareSum returns the proper result', () => {
expect(squareSum(2, 3, 4)).toBe(29);
});

View File

@ -9,4 +9,4 @@ test('Works with a callback.', () => {
});
test('Works with a property name.', () => {
expect(sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n')).toBe(20);
});
});

File diff suppressed because it is too large Load Diff

View File

@ -4,3 +4,8 @@ const {throttle} = require('./_30s.js');
test('throttle is a Function', () => {
expect(throttle).toBeInstanceOf(Function);
});
test('throttle returns a function', () => {
let throttled = throttle(x => x, 100000);
expect(throttled).toBeInstanceOf(Function);
expect(throttled(10)).toBe(undefined);
});

View File

@ -4,3 +4,9 @@ const {toHash} = require('./_30s.js');
test('toHash is a Function', () => {
expect(toHash).toBeInstanceOf(Function);
});
test('toHash works properly with indexes', () => {
expect(toHash([4, 3, 2, 1])).toEqual({ 0: 4, 1: 3, 2: 2, 3: 1 });
});
test('toHash works properly with keys', () => {
expect(toHash([{ a: 'label' }], 'a')).toEqual({ label: { a: 'label' } });
});

View File

@ -4,3 +4,9 @@ const {toggleClass} = require('./_30s.js');
test('toggleClass is a Function', () => {
expect(toggleClass).toBeInstanceOf(Function);
});
test('toggleClass toggles the class', () => {
let el = document.createElement('div');
el.classList.add('myClass');
toggleClass(el, 'myClass');
expect(el.classList.contains('myClass')).toBeFalsy();
});

View File

@ -4,3 +4,11 @@ const {triggerEvent} = require('./_30s.js');
test('triggerEvent is a Function', () => {
expect(triggerEvent).toBeInstanceOf(Function);
});
test('triggerEvent triggers an event', () => {
let el = document.createElement('div');
let val = false;
const fn = () => val = true;
el.addEventListener('click', fn);
triggerEvent(el, 'click', {});
expect(val).toBeTruthy();
});

View File

@ -17,3 +17,8 @@ test('Works with n = 2', () => {
test('Works with n = 3', () => {
expect(add3(1, 2, 3)).toBe(6);
});
test('Throws RangeError if arguments are too few', () => {
expect(() => {
add2(2);
}).toThrow(RangeError);
});

View File

@ -1123,7 +1123,7 @@
"hide": {
"prefix": "30s_hide",
"body": [
"const hide = els => els.forEach(e => (e.style.display = 'none'));"
"const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));"
],
"description": "Hides all the elements specified.\n\nUse `NodeList.prototype.forEach()` to apply `display: none` to each element specified"
},