Reputation: 18534
I've got a list with ~1000 possible file extensions and it's aliases. The structure looks like this:
var iconMap = [
{ icon: 'photoshop', extensions: ['psd'], format: 'svg' },
{ icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true },
{ icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' }]
I want to get the 'icon' property for the according extension. Therefore I want to create a getExtensionIcon(fileExtension)
function which should return:
var phpIcon = getExtensionIcon('php') // 'php'
var pharIcon = getExtensionIcon('phar') // 'php'
var php5Icon = getExtensionIcon('php5') // 'php'
My question:
I only got a few ideas which would be very ineffecient, so I am curious how you would realize the getExtensionicon function?
Upvotes: 0
Views: 667
Reputation: 1
Here is how I would do it - this "pre-processes" the iconMap once, creating an object that keys extension
with a value of icon
var iconMap = [
{ icon: 'photoshop', extensions: ['psd'], format: 'svg' },
{ icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true },
{ icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' }
];
var getExtensionIcon = (src => {
var extensions = src.filter(item => !item.disabled).reduce((result, item) => {
item.extensions.forEach(ext => {
result[ext] = item.icon;
});
return result;
}, {});
return ext => extensions[ext];
})(iconMap);
console.log('psd is', getExtensionIcon('psd'));
console.log('php1 is', getExtensionIcon('php1'));
Upvotes: 1
Reputation: 10096
If you can use jQuery, it has the $.grep()
function which seems like a good fit for this purpose:
function getExtensionIcon(arr, lang){
var result = $.grep(arr, function(e){ return e.extensions.indexOf(lang) != -1; });
return result[0].icon;
}
I don't really know how performant this is, but you should at least give it a try ;)
Testing with your Example:
function getExtensionIcon(arr, lang){
var result = $.grep(arr, function(e){ return e.extensions.indexOf(lang) != -1; });
return result[0].icon;
}
var iconMap = [
{ icon: 'photoshop', extensions: ['psd'], format: 'svg' },
{ icon: 'photoshop2', extensions: ['psd'], format: 'svg', disabled: true },
{ icon: 'php', extensions: ['php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'], format: 'svg' }];
console.log(getExtensionIcon(iconMap, "php6"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0