Created
July 22, 2019 07:55
-
-
Save js2me/efbf26f0a2bc2a37b13df0e524737e1c to your computer and use it in GitHub Desktop.
Basic helpers which reduce your code (most of them are polyfills)
This file contains 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
/** | |
* Check value on type which contains in arrayOfTypeNames | |
* | |
* | |
* Examples: | |
* valueIs('example', ['String']) -> true | |
* valueIs({}, ['String', 'Number']) -> false | |
* | |
* @param {any} value | |
* @param {string[]} arrayOfTypeNames | |
* @returns {boolean} true/false | |
*/ | |
export function valueIs(value, arrayOfTypeNames) { | |
return includes( | |
arrayOfTypeNames, | |
{}.toString.call(value).replace(/object|[ [\]]/g, '') | |
) | |
} | |
/** | |
* Check string or array on contains includedValue | |
* It is polyfill for {string|array}.includes(value) | |
* 'cause string.includes method is not supported in IE11- | |
* | |
* | |
* Example: | |
* includes('abc', 'a') -> true | |
* includes([1,2,3,4], 3) -> true | |
* | |
* @param {string|array} value | |
* @param {any} includedValue | |
* @returns {boolean} true if includedValue contains in value otherwise false | |
*/ | |
export function includes(value, includedValue) { | |
return value.indexOf(includedValue) > -1 | |
} | |
/** | |
* Do the same thing as includes() but takes array of included string values | |
* | |
* @param {string, array} value | |
* @param {string[]} includedValues | |
* @returns {boolean} true if some string contains in value | |
*/ | |
export function multiIncludes(value, includedValues) { | |
return includedValues | |
.map(includedValue => includes(value, includedValue)) | |
.some(isIncluded => isIncluded === true) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment