From 07fc5cd355f95890936a938e358679f019237942 Mon Sep 17 00:00:00 2001 From: 30secondsofcode <30secondsofcode@gmail.com> Date: Thu, 12 Apr 2018 18:45:32 +0000 Subject: [PATCH] Travis build: 1951 --- README.md | 76 ++++++++++++++++++++++++++++++++++++++++++ docs/adapter.html | 2 +- docs/array.html | 2 +- docs/browser.html | 2 +- docs/date.html | 2 +- docs/function.html | 23 ++++++++++++- docs/math.html | 2 +- docs/node.html | 2 +- docs/object.html | 12 ++++++- docs/string.html | 2 +- docs/type.html | 2 +- docs/utility.html | 2 +- snippets/hz.md | 10 +++--- snippets/renameKeys.md | 14 ++++---- 14 files changed, 132 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 500988992..5fe317292 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,7 @@ average(1, 2, 3); * [`defer`](#defer) * [`delay`](#delay) * [`functionName`](#functionname) +* [`hz`](#hz) * [`memoize`](#memoize) * [`negate`](#negate) * [`once`](#once) @@ -361,6 +362,7 @@ average(1, 2, 3); * [`orderBy`](#orderby) * [`pick`](#pick) * [`pickBy`](#pickby) +* [`renameKeys`](#renamekeys) * [`shallowClone`](#shallowclone) * [`size`](#size) * [`transform`](#transform) @@ -4272,6 +4274,50 @@ functionName(Math.max); // max (logged in debug channel of console)
[⬆ Back to top](#table-of-contents) +### hz + +Returns the number of times a function executed per second. +`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second. + +Use `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times. +Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. +Omit the second argument, `iterations`, to use the default of 100 iterations. + +```js +const hz = (fn, iterations = 100) => { + const before = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + return 1000 * iterations / (performance.now() - before); +}; +``` + +
+Examples + +```js +// 10,000 element array +const numbers = Array(10000) + .fill() + .map((_, i) => i); + +// Test functions with the same goal: sum up the elements in the array +const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0); +const sumForLoop = () => { + let sum = 0; + for (let i = 0; i < numbers.length; i++) sum += numbers[i]; + return sum; +}; + +// `sumForLoop` is nearly 10 times faster +Math.round(hz(sumReduce)); // 572 +Math.round(hz(sumForLoop)); // 4784 +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### memoize Returns the memoized (cached) function. @@ -6616,6 +6662,36 @@ pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3
[⬆ Back to top](#table-of-contents) +### renameKeys + +Replaces the names of multiple object keys with the values provided. + +Use `Object.keys()` in combination with `Array.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`. + +```js +const renameKeys = (keysMap, obj) => + Object.keys(obj).reduce( + (acc, key) => ({ + ...acc, + ...{ [keysMap[key] || key]: obj[key] } + }), + {} + ); +``` + +
+Examples + +```js +const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; +renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### shallowClone Creates a shallow clone of an object. diff --git a/docs/adapter.html b/docs/adapter.html index 5159c1acd..805bdeb0a 100644 --- a/docs/adapter.html +++ b/docs/adapter.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
 
const firstTwoMax = ary(Math.max, 2);
 [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
 

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
diff --git a/docs/array.html b/docs/array.html
index df07c4fb8..b970699fe 100644
--- a/docs/array.html
+++ b/docs/array.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Array

all

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const all = (arr, fn = Boolean) => arr.every(fn);
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Array

all

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const all = (arr, fn = Boolean) => arr.every(fn);
 
all([4, 2, 3], x => x > 1); // true
 all([1, 2, 3]); // true
 

any

Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.

Use Array.some() to test if any elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.

const any = (arr, fn = Boolean) => arr.some(fn);
diff --git a/docs/browser.html b/docs/browser.html
index f89976a59..812386700 100644
--- a/docs/browser.html
+++ b/docs/browser.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Browser

arrayToHtmlList

Converts the given array elements into <li> tags and appends them to the list of the given id.

Use Array.map() and document.querySelector() to create a list of html tags.

const arrayToHtmlList = (arr, listID) =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Browser

arrayToHtmlList

Converts the given array elements into <li> tags and appends them to the list of the given id.

Use Array.map() and document.querySelector() to create a list of html tags.

const arrayToHtmlList = (arr, listID) =>
   arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));
 
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
 

bottomVisible

Returns true if the bottom of the page is visible, false otherwise.

Use scrollY, scrollHeight and clientHeight to determine if the bottom of the page is visible.

const bottomVisible = () =>
diff --git a/docs/date.html b/docs/date.html
index 616b7625c..b147746b8 100644
--- a/docs/date.html
+++ b/docs/date.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Date

formatDuration

Returns the human readable format of the given number of milliseconds.

Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.

const formatDuration = ms => {
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Date

formatDuration

Returns the human readable format of the given number of milliseconds.

Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.

const formatDuration = ms => {
   if (ms < 0) ms = -ms;
   const time = {
     day: Math.floor(ms / 86400000),
diff --git a/docs/function.html b/docs/function.html
index 49aef3f4b..33c32be7b 100644
--- a/docs/function.html
+++ b/docs/function.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Function

attempt

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

Use a try... catch block to return either the result of the function or an appropriate error.

const attempt = (fn, ...args) => {
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Function

attempt

Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

Use a try... catch block to return either the result of the function or an appropriate error.

const attempt = (fn, ...args) => {
   try {
     return fn(...args);
   } catch (e) {
@@ -178,6 +178,27 @@ document.que
 ); // Logs 'later' after one second.
 

functionName

Logs the name of a function.

Use console.debug() and the name property of the passed method to log the method's name to the debug channel of the console.

const functionName = fn => (console.debug(fn.name), fn);
 
functionName(Math.max); // max (logged in debug channel of console)
+

hz

Returns the number of times a function executed per second. hz is the unit for hertz, the unit of frequency defined as one cycle per second.

Use performance.now() to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function iterations times. Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed. Omit the second argument, iterations, to use the default of 100 iterations.

const hz = (fn, iterations = 100) => {
+  const before = performance.now();
+  for (let i = 0; i < iterations; i++) fn();
+  return 1000 * iterations / (performance.now() - before);
+};
+
// 10,000 element array
+const numbers = Array(10000)
+  .fill()
+  .map((_, i) => i);
+
+// Test functions with the same goal: sum up the elements in the array
+const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
+const sumForLoop = () => {
+  let sum = 0;
+  for (let i = 0; i < numbers.length; i++) sum += numbers[i];
+  return sum;
+};
+
+// `sumForLoop` is nearly 10 times faster
+Math.round(hz(sumReduce)); // 572
+Math.round(hz(sumForLoop)); // 4784
 

memoize

Returns the memoized (cached) function.

Create an empty cache by instantiating a new Map object. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The function keyword must be used in order to allow the memoized function to have its this context changed if necessary. Allow access to the cache by setting it as a property on the returned function.

const memoize = fn => {
   const cache = new Map();
   const cached = function(val) {
diff --git a/docs/math.html b/docs/math.html
index e99ba6f86..3126c350d 100644
--- a/docs/math.html
+++ b/docs/math.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Math

approximatelyEqual

Checks if two numbers are approximately equal to each other.

Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Math

approximatelyEqual

Checks if two numbers are approximately equal to each other.

Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
 
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
 

average

Returns the average of two or more numbers.

Use Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.

const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
 
average(...[1, 2, 3]); // 2
diff --git a/docs/node.html b/docs/node.html
index ca0f40a9f..b664c4bce 100644
--- a/docs/node.html
+++ b/docs/node.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Node

atob

Decodes a string of data which has been encoded using base-64 encoding.

Create a Buffer for the given string with base-64 encoding and use Buffer.toString('binary') to return the decoded string.

const atob = str => new Buffer(str, 'base64').toString('binary');
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Node

atob

Decodes a string of data which has been encoded using base-64 encoding.

Create a Buffer for the given string with base-64 encoding and use Buffer.toString('binary') to return the decoded string.

const atob = str => new Buffer(str, 'base64').toString('binary');
 
atob('Zm9vYmFy'); // 'foobar'
 

btoa

Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

Create a Buffer for the given string with binary encoding and use Buffer.toString('base64') to return the encoded string.

const btoa = str => new Buffer(str, 'binary').toString('base64');
 
btoa('foobar'); // 'Zm9vYmFy'
diff --git a/docs/object.html b/docs/object.html
index db36e85ec..f603181d9 100644
--- a/docs/object.html
+++ b/docs/object.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Object

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.forEach() to return a function that uses Function.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Object

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.forEach() to return a function that uses Function.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
   fns.forEach(
     fn => (
       (f = obj[fn]),
@@ -292,6 +292,16 @@ Foo.prototypefilter(k => fn(obj[k], k))
     .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
 
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
+

renameKeys

Replaces the names of multiple object keys with the values provided.

Use Object.keys() in combination with Array.reduce() and the spread operator (...) to get the object's keys and rename them according to keysMap.

const renameKeys = (keysMap, obj) =>
+  Object.keys(obj).reduce(
+    (acc, key) => ({
+      ...acc,
+      ...{ [keysMap[key] || key]: obj[key] }
+    }),
+    {}
+  );
+
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
+renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
 

shallowClone

Creates a shallow clone of an object.

Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

const shallowClone = obj => Object.assign({}, obj);
 
const a = { x: true, y: 1 };
 const b = shallowClone(a); // a !== b
diff --git a/docs/string.html b/docs/string.html
index 41b2e7113..afaa7f870 100644
--- a/docs/string.html
+++ b/docs/string.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

String

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

String

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
 
byteSize('😀'); // 4
 byteSize('Hello World'); // 11
 

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
diff --git a/docs/type.html b/docs/type.html
index 527b5d59e..66b3a1a23 100644
--- a/docs/type.html
+++ b/docs/type.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Type

getType

Returns the native type of a value.

Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null.

const getType = v =>
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Type

getType

Returns the native type of a value.

Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null.

const getType = v =>
   v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
 
getType(new Set([1, 2, 3])); // 'set'
 

is

Checks if the provided value is of the specified type.

Ensure the value is not undefined or null using Array.includes(), and compare the constructor property on the value with type to check if the provided value is of the specified type.

const is = (type, val) => ![, null].includes(val) && val.constructor === type;
diff --git a/docs/utility.html b/docs/utility.html
index 21ab2abdb..24d3ed9fc 100644
--- a/docs/utility.html
+++ b/docs/utility.html
@@ -79,7 +79,7 @@
             document.getElementById('doc-drawer-checkbox').checked = false;
           }
         }, false);
-      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Utility

castArray

Casts the provided value as an array if it's not one.

Use Array.isArray() to determine if val is an array and return it as-is or encapsulated in an array accordingly.

const castArray = val => (Array.isArray(val) ? val : [val]);
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Utility

castArray

Casts the provided value as an array if it's not one.

Use Array.isArray() to determine if val is an array and return it as-is or encapsulated in an array accordingly.

const castArray = val => (Array.isArray(val) ? val : [val]);
 
castArray('foo'); // ['foo']
 castArray([1]); // [1]
 

cloneRegExp

Clones a regular expression.

Use new RegExp(), RegExp.source and RegExp.flags to clone the given regular expression.

const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
diff --git a/snippets/hz.md b/snippets/hz.md
index a9848fb55..08cff5de6 100644
--- a/snippets/hz.md
+++ b/snippets/hz.md
@@ -17,14 +17,16 @@ const hz = (fn, iterations = 100) => {
 
 ```js
 // 10,000 element array
-const numbers = Array(10000).fill().map((_, i) => i);
+const numbers = Array(10000)
+  .fill()
+  .map((_, i) => i);
 
 // Test functions with the same goal: sum up the elements in the array
 const sumReduce = () => numbers.reduce((acc, n) => acc + n, 0);
 const sumForLoop = () => {
-  let sum = 0
-  for (let i = 0; i < numbers.length; i++) sum += numbers[i]
-  return sum
+  let sum = 0;
+  for (let i = 0; i < numbers.length; i++) sum += numbers[i];
+  return sum;
 };
 
 // `sumForLoop` is nearly 10 times faster
diff --git a/snippets/renameKeys.md b/snippets/renameKeys.md
index 419062323..f8bb41dfe 100644
--- a/snippets/renameKeys.md
+++ b/snippets/renameKeys.md
@@ -5,12 +5,14 @@ Replaces the names of multiple object keys with the values provided.
 Use `Object.keys()` in combination with `Array.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`.
 
 ```js
-const renameKeys = (keysMap, obj) => Object
-    .keys(obj)
-    .reduce((acc, key) => ({
-        ...acc,
-        ...{ [keysMap[key] || key]: obj[key] }
-    }), {});
+const renameKeys = (keysMap, obj) =>
+  Object.keys(obj).reduce(
+    (acc, key) => ({
+      ...acc,
+      ...{ [keysMap[key] || key]: obj[key] }
+    }),
+    {}
+  );
 ```
 
 ```js