Last active
September 6, 2020 11:45
-
-
Save limxingzhi/eb71e255b3568ee21fe046e5c6b452bb to your computer and use it in GitHub Desktop.
This is an ES6 utilities script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // refer to https://xingzhi.dev/blog/common-js-snippets/ | |
| /** | |
| * This function returns a UUID | |
| * Taken from from https://stackoverflow.com/a/8809472/6622966 | |
| * | |
| * @return {string} A UUID in string | |
| * | |
| * @example | |
| */ | |
| function generateUUID() { // Public Domain/MIT | |
| var d = new Date().getTime(); | |
| if (typeof performance !== 'undefined' && typeof performance.now === 'function') { | |
| d += performance.now(); //use high-precision timer if available | |
| } | |
| return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { | |
| var r = (d + Math.random() * 16) % 16 | 0; | |
| d = Math.floor(d / 16); | |
| return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); | |
| }); | |
| } | |
| /** | |
| * This function throttles a function | |
| * https://gist.github.com/beaucharman/e46b8e4d03ef30480d7f4db5a78498ca | |
| * https://www.30secondsofcode.org/js/s/throttle | |
| * | |
| * @param {function} callback - The callback function to invoke | |
| * @param {number} wait - The number of milliseconds to wait before invoking the callback | |
| * @param {namespace} context - The namespace to invoke the callback | |
| */ | |
| function throttle(callback, wait, context = this) { | |
| let timeout = null | |
| let callbackArgs = null | |
| const later = () => { | |
| callback.apply(context, callbackArgs) | |
| timeout = null | |
| } | |
| return function () { | |
| if (!timeout) { | |
| callbackArgs = arguments | |
| timeout = setTimeout(later, wait) | |
| } | |
| } | |
| } | |
| /** | |
| * This function throttles a function | |
| * https://gist.github.com/beaucharman/1f93fdd7c72860736643d1ab274fee1a | |
| * https://www.30secondsofcode.org/js/s/debounce | |
| * | |
| * @param {function} callback - The callback function to invoke | |
| * @param {number} wait - The number of milliseconds to wait before invoking the callback | |
| * @param {boolean} immediate - Whether to invoke the function immediately | |
| */ | |
| function debounce(callback, wait, immediate = false) { | |
| let timeout = null | |
| return function () { | |
| const callNow = immediate && !timeout | |
| const next = () => callback.apply(this, arguments) | |
| clearTimeout(timeout) | |
| timeout = setTimeout(next, wait) | |
| if (callNow) { | |
| next() | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment