Skip to content

Commit

Permalink
fix: add file extension util (#488)
Browse files Browse the repository at this point in the history
* fix: add file extension util

* chore: add link to SO post
  • Loading branch information
spaenleh authored Apr 19, 2024
1 parent 147d8d2 commit 1f04dd9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/item/fileItem/fileItem.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';

import { getFileExtension } from './fileItem.js';

describe('File Item utils', () => {
describe('getFileExtension', () => {
it('Simple extensions', () => {
expect(getFileExtension('sample.txt')).toEqual('.txt');
expect(getFileExtension('sample.jpeg')).toEqual('.jpeg');
expect(getFileExtension('s.t')).toEqual('.t');
});
it('Simple extensions without dots', () => {
expect(getFileExtension('sample.txt', { includeDot: false })).toEqual(
'txt',
);
expect(
getFileExtension('sample.test.txt', { includeDot: false }),
).toEqual('txt');
});
it('Filename with multiple extensions', () => {
expect(getFileExtension('sample.test.txt')).toEqual('.txt');
expect(getFileExtension('sample.test.hello.wow.txt')).toEqual('.txt');
});
it('No extensions return undefined', () => {
expect(getFileExtension('sample')).toEqual(undefined);
expect(getFileExtension('sample.')).toEqual(undefined);
});
});
});
21 changes: 21 additions & 0 deletions src/item/fileItem/fileItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,27 @@ export const buildS3FileExtra = (
[ItemType.S3_FILE]: extra,
});

/**
* Extract extension from filename.
* @param fileName Name of the file to get the extension from
* @param options Options object, currently contains `includeDot` to return the extension with a leading dot, for easy concatenation, this option is true by default
* @returns
*/
export const getFileExtension = (
fileName: string,
{ includeDot = true } = {},
): string | undefined => {
// this code has been adapted from https://stackoverflow.com/a/680982
const extensionRegex = /(?:\.([^.]+))?$/;
const extension = extensionRegex.exec(fileName)?.[1];
if (extension) {
if (includeDot) {
return `.${extension}`;
}
return extension;
}
};

/**
* File Settings
*/
Expand Down

0 comments on commit 1f04dd9

Please sign in to comment.