dimanche 22 juillet 2018

Check if file name end matches to any string in array [duplicate]

This question already has an answer here:

Problem

I have a file and want to check whether it ends with a certain extension. Depending on that, I want to proceed. For now, my code contains a lot of file.name.endswith(X) || file.name.endswith(Y) expressions:

if (file.name.endsWith('.nii') || file.name.endsWith('.nii.gz') ||
    file.name.endsWith('.fif') || file.name.endsWith('.fif.gz') ||
    file.name.endsWith('.sqd') || file.name.endsWith('con') ||
    file.name.endsWith('kdf') || file.name.endsWith('chn') ||
    file.name.endsWith('trg') || file.name.endsWith('raw') ||
    file.name.endsWith('raw.mhd')) {}

Question

What would be an elevant way to solve this using a single logical expression against an array of potential matches?

Something like (pseudocode) if file.name.endsWith.anyOf([*array of file endings*])

Previous work

I have looked at two solutions from this post and this is what I have come up with so far:

  1. Using RegExp, but it is suboptimal, because I am using the last 4 letters and thus have to truncate some file endings (e.g., .raw.mhd becomes .mhd to fit the 4 last letters):

RegExp('\.nii|i\.gz|\.fif|f\.gz|\.sqd|\.con|\.kdf|\.chn|\.trg|\.raw|\.mhf').test(file.name.slice(-4))

  1. Using indexOf, but it does not evaluate to true so there must be a mistake:

else if (file.name.indexOf('.nii .nii.gz .fif .fif.gz .sqd .con .kdf .chn .trg .raw .raw.mhd') !== -1) {

Aucun commentaire:

Enregistrer un commentaire