Returns a random element from an array, using the provided weights as the probabilities for each element.

Use Array.prototype.reduce() to create an array of partial sums for each value in weights.
Use Math.random() to generate a random number and Array.prototype.findIndex() to find the correct index based on the array previously produced.
Finally, return the element of arr with the produced index.

继续阅读 30秒学会 JavaScript 片段 – weightedSample

Creates a new object from the combination of two or more objects.

Use Array.prototype.reduce() combined with Object.keys(obj) to iterate over all objects and keys.
Use hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.

继续阅读 30秒学会 JavaScript 片段 – merge

Add special characters to text to print in color in the console (combined with console.log()).

Use template literals and special characters to add the appropriate color code to the string output.
For background colors, add a special character that resets the background color at the end of the string.

继续阅读 30秒学会 JavaScript 片段 – colorize

Returns a customized coalesce function that returns the first argument that returns true from the provided argument validation function.

Use Array.prototype.find() to return the first argument that returns true from the provided argument validation function.

继续阅读 30秒学会 JavaScript 片段 – coalesceFactory

Creates an array of key-value pair arrays from an object or other iterable (object, array, string, set etc.).

Check if Symbol.iterator is defined and, if so, use Array.prototype.entries() to get an iterator for the given iterable, Array.from() to convert the result to an array of key-value pair arrays.
If Symbol.iterator is not defined for obj, use Object.entries() instead.

继续阅读 30秒学会 JavaScript 片段 – toPairs