sromexs v2.6.7
Sromexs Documentation
Sromexs is a utility class that provides various helpful methods for working with arrays, strings, files, and other general tasks. Below is the documentation for the methods available in the Sromexs class, along with examples for each one.
Table of Contents
- uniqueByProp
- unique
- sleep
- strIncludeStr
- arrFilterByStr
- arrIncludesStr
- arrDifference
- readTxtFile
- readJsonFile
- writeJsonFile
- writeTxtFile
- timeoutPromise
- persianNumToEn
- arabicNumToEn
- arabicCharToPersian
- writeJsonLastNArray
- appendJsonLastNArray
- appendJsonFile
- removeFromJsonArrayFile
- findFromJsonArrayFile
- addToJsonArrayFile
- icons
- mkdir
- rm
- chunk
- shuffle
- checkConnection
- escapeStringRegExp
- sample
- getRandomItem
uniqueByProp
Returns an array of objects with unique values based on a specified property.
uniqueByProp<T>(array: T[], prop: string): T[];
Example:
const data = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'John' },
{ id: 4, name: 'Jim' },
];
const uniqueData = sr.uniqueByProp(data, 'name');
console.log(uniqueData);
// Output: [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 4, name: 'Jim' } ]
unique
Returns an array with unique values (no duplicates).
unique<T>(arr: T[]): T[];
Example:
const arr = [1, 2, 3, 1, 4, 3];
const uniqueArr = sr.unique(arr);
console.log(uniqueArr);
// Output: [1, 2, 3, 4]
sleep
Asynchronous sleep function that waits for a specified time in milliseconds.
sleep(ms: number, maxWait?: number): Promise<void>;
Example:
async function delay() {
console.log('Start');
await sr.sleep(2000);
console.log('End (after 2 seconds)');
}
delay();
// Output: Start -> [2 seconds delay] -> End (after 2 seconds)
strIncludeStr
Checks if a string contains any of the specified substrings.
strIncludeStr(str: string, include: string[] | string): boolean;
Example:
const text = 'Hello, world!';
console.log(sr.strIncludeStr(text, 'world'));
// Output: true
console.log(sr.strIncludeStr(text, ['Hi', 'world']));
// Output: true
arrFilterByStr
Filters an array of strings by excluding elements containing specified substrings.
arrFilterByStr(strArr: string[], filter: string[] | string): string[];
Example:
const words = ['apple', 'banana', 'orange', 'grape'];
const filteredWords = sr.arrFilterByStr(words, 'a');
console.log(filteredWords);
// Output: ['orange', 'grape']
arrIncludesStr
Filters an array of strings by including only elements containing specified substrings.
arrIncludesStr(strArr: string[], include: string | string[]): string[];
Example:
const words = ['apple', 'banana', 'orange', 'grape'];
const includedWords = sr.arrIncludesStr(words, ['ap', 'ra']);
console.log(includedWords);
// Output: ['apple', 'grape']
arrDifference
Returns the elements that are present in the first array but not in the second array.
arrDifference(firstArr: string[], secondArr: string[]): string[];
Example:
const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['b', 'd'];
const diff = sr.arrDifference(arr1, arr2);
console.log(diff);
// Output: ['a', 'c']
readTxtFile
Reads the contents of a text file.
readTxtFile(path: string): string;
Example:
Suppose there is a file named sample.txt
with the following content:
Hello, world!
This is a sample text file.
const filePath = 'sample.txt';
const fileContent = sr.readTxtFile(filePath);
console.log(fileContent);
// Output: "Hello, world!\nThis is a sample text file."
readJsonFile
Reads the contents of a JSON file and parses it to a JavaScript object.
readJsonFile<T>(path: string, defaultValue: T): T;
Example:
Suppose there is a file named data.json
with the following content:
{
"name": "John",
"age": 30
}
const filePath = 'data.json';
const defaultData = { name: '', age: 0 };
const jsonData = sr.readJsonFile(filePath, defaultData);
console.log(jsonData);
// Output: { name: 'John', age: 30 }
writeJsonFile
Writes a JavaScript object to a JSON file.
writeJsonFile(path: string, data: any): void;
Example:
const data = { name: 'John', age: 30 };
const filePath = 'output.json';
sr.writeJsonFile(filePath, data);
Contents of output.json
after execution:
{
"name": "John",
"age": 30
}
writeTxtFile
Writes a string to a text file.
writeTxtFile(path: string, data: string): void;
Example:
const text = 'Hello, world!';
const filePath = 'output.txt';
sr.writeTxtFile(filePath, text);
Contents of output.txt
after execution:
Hello, world!
timeoutPromise
Wraps a promise with a timeout.
timeoutPromise<T>(promise: () => Promise<T>, timeout: number): Promise<T>;
Example:
async function fetchData() {
try {
const data = await sr.timeoutPromise(fetchDataFromServer, 5000);
console.log('Data received:', data);
} catch (err) {
console.log('Error:', err.message);
}
}
fetchData();
// Output: Data received: [data from the server]
// or
// Output: Error: timeout of 5000 ms exceeded
persianNumToEn
Converts Persian numeric characters (۰-۹) to English numeric characters (0-9).
persianNumToEn(str: string): string;
Example:
const persianText = '۱۲۳۴۵';
const englishText = sr.persianNumToEn(persianText);
console.log(englishText);
// Output: '12345'
arabicNumToEn
Converts Arabic numeric characters (٠-٩) to English numeric characters (0-9).
arabicNumToEn(str: string): string;
Example:
const arabicText = '١٢٣٤٥';
const englishText = sr.arabicNumToEn(arabicText);
console.log(englishText);
// Output: '12345'
arabicCharToPersian
Converts Arabic characters to Persian characters.
arabicCharToPersian(str: string): string;
Example:
const arabicText = 'كِدِبِذِشِسِىي١٢٣٤٥٦٧٨٩٠';
const persianText = sr.arabicCharToPersian(arabicText);
console.log(persianText);
// Output: 'کدبذشسیی۱۲۳۴۵۶۷۸۹۰'
writeJsonLastNArray
Writes the last N elements of an array to a JSON file.
writeJsonLastNArray<T>(
path: string,
data: T[],
len = 100,
options?: writeJsonLastNArrayOptions
): void;
Example:
const data = [1, 2, 3, 4, 5];
const filePath = 'output.json';
sr.writeJsonLastNArray(filePath, data, 3);
Contents of output.json
after execution:
[3, 4, 5]
appendJsonLastNArray
Appends the last N elements of an array to a JSON file.
appendJsonLastNArray<T>(
path: string,
data: T[],
len = 100,
options?: appendJsonLastNArrayOptions
): void;
Example:
Suppose there is a file named data.json
with the following content:
[1, 2, 3]
const data = [4, 5, 6];
const filePath = 'data.json';
sr.appendJsonLastNArray(filePath, data, 4);
Contents of data.json
after execution:
[3, 4, 5, 6]
appendJsonFile
Appends data to a JSON file.
appendJsonFile<T>(path: string, data: T[]): void;
Example:
Suppose there is a file named data.json
with the following content:
[1, 2, 3]
const data = [4, 5, 6];
const filePath = 'data.json';
sr.appendJsonFile(filePath, data);
Contents of data.json
after execution:
[4, 5, 6, 1, 2, 3]
removeFromJsonArrayFile
Removes elements from a JSON array file based on a specified property and value.
removeFromJsonArrayFile(path: string, prop: string, value: string): void;
Example:
Suppose there is a file named data.json
with the following content:
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" },
{ "id": 3, "name": "John" }
]
const filePath = 'data.json';
sr.removeFromJsonArrayFile(filePath, 'name', 'John');
Contents of data.json
after execution:
[
{ "id": 2, "name": "Jane" }
]
findFromJsonArrayFile
Finds an element in a JSON array file based on a specified property and value.
findFromJsonArrayFile<T>(path: string, def: T[], prop: string, value: string): T | undefined;
Example:
Suppose there is a file named data.json
with the following content:
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" },
{ "id": 3, "name": "John" }
]
const filePath = 'data.json';
const defaultValue = [];
const foundItem = sr.findFromJsonArrayFile(filePath, defaultValue, 'name', 'Jane');
console.log(foundItem);
// Output: { "id": 2, "name": "Jane" }
addToJsonArrayFile
Adds an item to a JSON array file.
addToJsonArrayFile<T>(path: string, item: T): void;
Example:
Suppose there is a file named data.json
with the following content:
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" }
]
const newItem = { "id": 3, "name": "Alice" };
const filePath = 'data.json';
sr.addToJsonArrayFile(filePath, newItem);
Contents of data.json
after execution:
[
{ "id": 1, "name": "John" },
{ "id": 2, "name": "Jane" },
{ "id": 3, "name": "Alice" }
]
icons
Returns a set of Unicode or fallback icons based on the platform.
icons(): { info: string, success: string, warning: string, error: string };
Example:
const icons = sr.icons();
console.log(icons);
// Output on a Unicode-supported platform:
{ info: 'ℹ', success: '✔', warning: '⚠', error: '✖' }
// Output on a non-Unicode-supported platform: { info: 'i', success: '√', warning: '‼', error: '×' }
mkdir
Creates directories if they don't exist.
mkdir(dirnames: string | string[]): void;
Example:
const directories = ['logs', 'data'];
sr.mkdir(directories);
The above code will create directories named logs
and data
if they do not exist.
rm
Removes directories and their contents.
rm(dirnames: string | string[]): void;
Example:
const directories = ['temp', 'cache'];
sr.rm(directories);
The above code will remove directories named temp
and cache
along with their contents.
chunk
Splits an array into smaller arrays of a specified size.
chunk<T>(array: T[], size = 1): T[][];
Example:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunks = sr.chunk(numbers, 3);
console.log(chunks);
// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
shuffle
Randomly shuffles the elements of an array.
shuffle<T>(array: T[]): T[];
Example:
const arr = [1, 2, 3, 4, 5];
const shuffledArr = sr.shuffle(arr);
console.log(shuffledArr);
// Output: [4, 2, 1, 5, 3] (randomly shuffled)
checkConnection
Checks internet connectivity using DNS lookup.
checkConnection(): Promise<boolean>;
Example:
async function checkInternetConnection() {
const isConnected = await sr.checkConnection();
console.log('Internet connectivity:', isConnected ? 'Available' : 'Not available');
}
checkInternetConnection();
// Output: Internet connectivity: Available or Internet connectivity: Not available
escapeStringRegExp
Escapes special characters in a string for use in a regular expression.
escapeStringRegExp(str: string): string;
Example:
const input = 'Hello [world]';
const escaped = sr.escapeStringRegExp(input);
console.log(escaped);
// Output: 'Hello \\[world\\]'
sample
Returns a random element from an array.
sample<T>(array: T[]): T;
Example:
const items = [1, 2, 3, 4, 5];
const randomItem = sr.sample(items);
console.log(randomItem);
// Output: (randomly selected element from the array)
getRandomItem
Returns a specified number of random elements from an array.
getRandomItem<T>(array: T[], size: number = 1): T[];
Example:
const items = [1, 2, 3, 4, 5];
const randomItems = sr.getRandomItem(items, 3);
console.log(randomItems);
// Output: (3 randomly selected elements from the array)
This concludes the documentation for the Sromexs utility class. Use these methods to simplify and enhance various tasks in your Node.js applications. If you have any questions or need further assistance, feel free to reach out!
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago