diff --git a/README.md b/README.md index e29735d..f7e158f 100644 --- a/README.md +++ b/README.md @@ -89,55 +89,69 @@ fileEasy.saveDocument(filename, content) ## Functions
string
Append specified extension if needed.
-Save content in a file using utf8 format.
string
Append specified extension if needed.
+string
Convert a string into an identifier.
string
-Append specified extension if needed.
+## saveDocument(filename, content)
+Save content in a file using utf8 format.
+
+**Kind**: global function
+**Throws**:
+
+- Error
If input is invalid or if there was an error during the save process.
-**Kind**: global function
-**Returns**: string
- filename with either existing or specified extension
| Param | Type | Description |
| --- | --- | --- |
-| filename | string
| the filename to check for an existing extension. |
-| extension | string
| the extension to append if filename has no extension. It should start with a dot (e.g. `.txt`) |
+| filename | string
| The filename to create. It can also include a path ending with the filename. Path will be created if not exists. |
+| content | string
| The content to place in the file. |
-
+
-## saveDocument(filename, content)
-Save content in a file using utf8 format.
+## setDefaultExtension(filename, extension) ⇒ string
+Append specified extension if needed.
+
+**Kind**: global function
+**Returns**: string
- filename with either existing or specified extension
+**Throws**:
+
+- TypeError
If filename or extension is not a string.
+- Error
If extension is empty or doesn't start with a dot.
-**Kind**: global function
| Param | Type | Description |
| --- | --- | --- |
-| filename | string
| The filename to create. It can also include a path ending with the filename. Path will be created if not exists. |
-| content | string
| The content to place in the file. |
+| filename | string
| The filename to check for an existing extension. |
+| extension | string
| The extension to append if filename has no extension. It should start with a dot (e.g. `.txt`) |
## slug(s) ⇒ string
Convert a string into an identifier.
-**Kind**: global function
-**Returns**: string
- The identifier string
+**Kind**: global function
+**Returns**: string
- The identifier string.
+
+The following operations are performed on the string:
+1. Trim and convert to lower case.
+2. Remove diacritics (transliterate or remove non-ASCII characters).
+3. Replace spaces and special characters with hyphens, allowing underscores.
+4. Replace multiple hyphens with a single hyphen.
+5. Remove leading and trailing hyphens.
| Param | Type | Description |
| --- | --- | --- |
-| s | string
| The string to convert by replacing special characters with dash (-) |
-
-
+| s | string
| The string to convert. |
## Author
diff --git a/slug.test.js b/__tests__/file-easy.test.js
similarity index 61%
rename from slug.test.js
rename to __tests__/file-easy.test.js
index 4e3ba0c..fcd8dbf 100644
--- a/slug.test.js
+++ b/__tests__/file-easy.test.js
@@ -1,4 +1,4 @@
-const { slug, setDefaultExtension, saveDocument } = require('./index'); // Adjust path if necessary
+const { slug, setDefaultExtension, saveDocument } = require('../index'); // Adjust path if necessary
const fs = require('fs');
const path = require('path');
@@ -30,23 +30,56 @@ describe('slug', () => {
});
-
-
describe('setDefaultExtension', () => {
+ it('should throw an error for an extension without a leading dot', () => {
+ const filename = 'example';
+ const invalidExtension = 'txt';
+ expect(() => setDefaultExtension(filename, invalidExtension)).toThrow('Invalid extension: must start with a dot and contain only alphanumeric characters.');
+ });
- it('should return filename with default extension', () => {
-
- expect(setDefaultExtension('myfile', '.md')).toBe('myfile.md');
+ it('should throw an error for an extension with invalid characters', () => {
+ const filename = 'example';
+ const invalidExtension = '.tx$t';
+ expect(() => setDefaultExtension(filename, invalidExtension)).toThrow('Invalid extension: must start with a dot and contain only alphanumeric characters.');
});
+ it('should not throw an error for a valid extension', () => {
+ const filename = 'example';
+ const validExtension = '.txt';
+ expect(() => setDefaultExtension(filename, validExtension)).not.toThrow();
+ });
+ it('should return the filename with the default extension if no extension is present', () => {
+ const filename = 'example';
+ const extension = '.txt';
+ const result = setDefaultExtension(filename, extension);
+ expect(result).toBe('example.txt');
+ });
- it('should return filename with existing extension', () => {
+ it('should return the original filename if it already has an extension', () => {
+ const filename = 'example.txt';
+ const extension = '.md';
+ const result = setDefaultExtension(filename, extension);
+ expect(result).toBe('example.txt');
+ });
- expect(setDefaultExtension('myfile.txt', '.md')).toBe('myfile.txt');
+ it('should throw an error if filename is not a string', () => {
+ const invalidFilename = 12345;
+ const extension = '.txt';
+ expect(() => setDefaultExtension(invalidFilename, extension)).toThrow('Invalid input: `filename` must be a string.');
+ });
+ it('should throw an error if extension is not a string', () => {
+ const filename = 'example';
+ const invalidExtension = 12345;
+ expect(() => setDefaultExtension(filename, invalidExtension)).toThrow('Invalid input: `extension` must be a string.');
});
+ it('should throw an error if filename is empty', () => {
+ const emptyFilename = '';
+ const extension = '.txt';
+ expect(() => setDefaultExtension(emptyFilename, extension)).toThrow('Invalid input: `filename` cannot be empty.');
+ });
});
diff --git a/index.js b/index.js
index fdf9948..43820c0 100644
--- a/index.js
+++ b/index.js
@@ -2,17 +2,6 @@ const path = require('path')
const fs = require('fs')
-/**
- * Append specified extension if needed.
- *
- * @param {string} filename the filename to check for an existing extension.
- * @param {string} extension the extension to append if filename has no extension. It should start with a dot (e.g. `.txt`)
- * @returns {string} filename with either existing or specified extension
- */
-function setDefaultExtension(filename, extension) {
- return (path.extname(filename)) ? filename : filename + extension;
-}
-
/**
* Save content in a file using utf8 format.
*
@@ -47,6 +36,40 @@ function saveDocument(filename, content) {
fs.writeFileSync(filename, content, 'utf8');
}
+/**
+ * Append specified extension if needed.
+ *
+ * @param {string} filename The filename to check for an existing extension.
+ * @param {string} extension The extension to append if filename has no extension. It should start with a dot (e.g. `.txt`)
+ * @returns {string} filename with either existing or specified extension
+ * @throws {TypeError} If filename or extension is not a string.
+ * @throws {Error} If extension is empty or doesn't start with a dot.
+ */
+function setDefaultExtension(filename, extension) {
+ // Validate inputs
+ const validExtensionPattern = /^\.[a-zA-Z0-9]+$/;
+ if (typeof filename !== 'string') {
+ throw new TypeError('Invalid input: `filename` must be a string.');
+ }
+ if (typeof extension !== 'string') {
+ throw new TypeError('Invalid input: `extension` must be a string.');
+ }
+ if (filename.trim() === '') {
+ throw new Error('Invalid input: `filename` cannot be empty.');
+ }
+
+ // Validate extension
+ if (!validExtensionPattern.test(extension)) {
+ throw new Error('Invalid extension: must start with a dot and contain only alphanumeric characters.');
+ }
+
+ // Return filename with existing extension, or append the specified extension
+ if (path.extname(filename)) {
+ return filename;
+ }
+
+ return `${filename}${extension}`;
+}
/**
* Convert a string into an identifier.
@@ -83,10 +106,8 @@ function slug(s) {
return s;
}
-
-
module.exports = {
- slug: slug,
- setDefaultExtension: setDefaultExtension,
- saveDocument: saveDocument
+ saveDocument,
+ setDefaultExtension,
+ slug,
}
\ No newline at end of file
diff --git a/output.md b/output.md
new file mode 100644
index 0000000..0ed445b
--- /dev/null
+++ b/output.md
@@ -0,0 +1,60 @@
+## Functions
+
+Save content in a file using utf8 format.
+string
Append specified extension if needed.
+string
Convert a string into an identifier.
+Error
If input is invalid or if there was an error during the save process.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| filename | string
| The filename to create. It can also include a path ending with the filename. Path will be created if not exists. |
+| content | string
| The content to place in the file. |
+
+
+
+## setDefaultExtension(filename, extension) ⇒ string
+Append specified extension if needed.
+
+**Kind**: global function
+**Returns**: string
- filename with either existing or specified extension
+**Throws**:
+
+- TypeError
If filename or extension is not a string.
+- Error
If extension is empty or doesn't start with a dot.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| filename | string
| The filename to check for an existing extension. |
+| extension | string
| The extension to append if filename has no extension. It should start with a dot (e.g. `.txt`) |
+
+
+
+## slug(s) ⇒ string
+Convert a string into an identifier.
+
+**Kind**: global function
+**Returns**: string
- The identifier string.
The following operations are performed on the string:
1. Trim and convert to lower case.
2. Remove diacritics (transliterate or remove non-ASCII characters).
3. Replace spaces and special characters with hyphens, allowing underscores.
4. Replace multiple hyphens with a single hyphen.
5. Remove leading and trailing hyphens.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| s | string
| The string to convert. |
+
diff --git a/spec/file-easy-spec.js b/spec/file-easy-spec.js
deleted file mode 100644
index 3d0c3a0..0000000
--- a/spec/file-easy-spec.js
+++ /dev/null
@@ -1,78 +0,0 @@
-const fs = require('fs');
-const path = require('path');
-const fu = require('../index');
-
-
-describe('file-easy', () => {
-
- describe('file-easy.slug()', () => {
-
- it('should return empty on empty or all spaces', () => {
- let r = fu.slug('')
- expect(r).toEqual('')
- r = fu.slug(' ')
- expect(r).toEqual('')
- })
-
- it('should return empty on all special characters', () => {
- let r = fu.slug('#$%^&*')
- expect(r).toEqual('')
- })
-
- it('should return all lowercase', () => {
- let r = fu.slug('StrInG')
- expect(r).toEqual('string')
- })
-
- it('should replace special characters with dash (-)', () => {
- let r = fu.slug('Str $*()InG')
- expect(r).toEqual('str-ing')
- })
-
- it('should not have dash(-) as heading or trailing', () => {
- let r = fu.slug('%% ()@@Str $*()InG&*^%$#')
- expect(r).toEqual('str-ing')
- })
-
-
- })
-
- describe('file-easy.setDefaultExtension()', () => {
-
- it('should return the initial filename if extension present', () => {
- let r = fu.setDefaultExtension('filename.js', '.json')
- expect(r).toEqual('filename.js')
- })
-
- it('should return filename and default extension if extension missing', () => {
- let r = fu.setDefaultExtension('filename', '.json')
- expect(r).toEqual('filename.json')
- })
-
- it('should return the initial filename if extension is a single dot(.)', () => {
- let r = fu.setDefaultExtension('filename.', '.json')
- expect(r).toEqual('filename.')
- })
- })
-
- describe('file-easy.saveDocument()', () => {
-
- it('should save the file in local folder', () => {
- let filename = path.join(__dirname, 'sample.txt')
- if (fs.existsSync(filename))
- fs.unlinkSync(filename);
- fu.saveDocument(filename, 'Content')
- let r = fs.existsSync(filename)
- expect(r).toEqual(true)
- })
-
- it('should save the file in local subfolder folder', () => {
- let filename = path.join(__dirname, 'sample', 'sample.txt')
- if (fs.existsSync(filename))
- fs.unlinkSync(filename);
- fu.saveDocument(filename, 'Content')
- let r = fs.existsSync(filename)
- expect(r).toEqual(true)
- })
- })
-})
\ No newline at end of file
diff --git a/spec/support/jasmine.json b/spec/support/jasmine.json
deleted file mode 100644
index 370fc44..0000000
--- a/spec/support/jasmine.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "spec_dir": "spec",
- "spec_files": [
- "**/*[sS]pec.js"
- ],
- "helpers": [
- "helpers/**/*.js"
- ],
- "stopSpecOnExpectationFailure": false,
- "random": true
-}