Last active
April 5, 2018 22:33
-
-
Save gabemeola/ed76e0c38c9c2013c11e29f653915680 to your computer and use it in GitHub Desktop.
Validate All Images in Array.
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
import fetchImage from 'https://gist.githubusercontent.com/gabemeola/27e8fd9148f9ae7541d88d54d87f5113/raw/97138b8039f3b598c41832ef4bfdd4e48bcb3ab6/fetchImage.js' | |
const noop = () => {} | |
function removeUrlProtocol(url) { | |
// Split the image to not include protocol | |
const srcSplit = url.split(':'); | |
// Use the second part of the protocol string | |
// split, if it exists. | |
return srcSplit[1] ? srcSplit[1] : srcSplit[0]; | |
} | |
/** | |
* Takes an Array on Images and returns | |
* which images a valid. | |
* | |
* Can be configure with a custom config object. | |
* | |
* @param {Array.<string>} images - Images to validate | |
* @param {Object=} [config] - Configuration object | |
* @param {number | null} [config.validateLimit = null] - Limit on validation loop. Starting at beginning of Array | |
* @param {boolean} [config.stopOnFound = false] - Whether to stop once an image is found. | |
* Not guarantied because ~Promises~. | |
* @return {Promise.<Array<string>>} - Array of valid images | |
*/ | |
export default async function validateImages(images, { | |
validateLimit = null, | |
stopOnFound = false, | |
} = {}) { | |
let found = false; | |
const imagePromises = []; | |
const foundSwitcher = (imageUrl) => { | |
found = true; | |
return imageUrl; | |
}; | |
for (let i = 0; i < images.length; i += 1) { | |
const image = removeUrlProtocol(images[i]); | |
// Break out if we reached the limit | |
if (i === validateLimit - 1) break; | |
// Break out if we found an image, | |
// and this functionality is turned on. | |
// We wil most likely get more than one image found | |
// because Promises are async. | |
if (stopOnFound && found) break; | |
const fetchPromise = fetchImage(image) | |
.then(foundSwitcher) | |
.catch(noop); | |
imagePromises.push(fetchPromise); | |
} | |
return Promise | |
.all(imagePromises) | |
.then((res) => res.filter(Boolean)) | |
.catch((e) => { | |
// Re-throw error | |
throw e; | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment