Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
react-tesna-utils
Advanced tools
A versatile utility library featuring optimized functions for data manipulation, clipboard handling, text truncation, comparison, validation, and more. Designed for modern JavaScript and TypeScript projects with efficient and reusable solutions.
convertTimeToMilliseconds
The convertTimeToMilliseconds
function takes a time value and a unit (s
for seconds, m
for minutes, or h
for hours) and converts the time into milliseconds. This
is useful for standardizing time values across various formats.
import { convertTimeToMilliseconds } from 'react-tesna-utils';
// Convert 5 seconds to milliseconds
const timeInMilliseconds1 = convertTimeToMilliseconds(5, 's'); // Output: 5000
// Convert 2 hours to milliseconds
const timeInMilliseconds3 = convertTimeToMilliseconds(2, 'h'); // Output: 7200000
time
(number
): The time value you want to convert.unit
(TTimeUnit
): The unit of time, which can be:
-'s'
for seconds,
-'m'
for minutes,'h'
for hours.number
: The equivalent time in milliseconds.fn_deadline
Calculates a deadline timestamp based on the current time and a provided time duration in the format hh:mm:ss
.
import { fn_deadline } from 'react-tesna-utils';
// Calculate a deadline 2 hours, 30 minutes, and 45 seconds from the current time
const deadlineTimestamp = fn_deadline("02:30:45");
// Calculate a deadline 15 minutes from the current time
const shortDeadline = fn_deadline("00:15:00");
formatCadNumber
Formats a credit card or similar numeric string by adding hyphens every four digits for improved readability.
import { formatCadNumber } from 'react-tesna-utils';
// Format a 16-digit card number
const formattedCardNumber = formatCadNumber("1234567812345678");
// Output: "1234 - 5678 - 1234 - 5678"
// Format a 9-digit number
const formattedShortNumber = formatCadNumber("123456789");
// Output: "1234 - 5678 - 9"
formatNumber
Formats a number as a localized string with up to 10 decimal places, using the user's locale for number formatting.
import { formatNumber } from 'react-tesna-utils';
// Format a number
const formattedNumber = formatNumber(1234567.890123);
// Output: "1,234,567.890123"
// Format a large number with no decimals
const formattedLargeNumber = formatNumber(9876543210);
// Output: "9,876,543,210"
formatPhoneNumber
Formats a phone number string by cleaning non-numeric characters and arranging it in a standardized format.
import { formatPhoneNumber } from 'react-tesna-utils';
// Format a phone number with extra characters
const formattedPhoneNumber = formatPhoneNumber('0912-345-6789');
// Output: "(0912) 345-6789"
// Format a phone number with country code
const formattedPhoneNumberWithCountryCode = formatPhoneNumber('+989123456789');
// Output: "(0912) 345-6789"
// Invalid phone number
const invalidPhoneNumber = formatPhoneNumber('12345');
// Output: null
generateRandomNumber
Generates a random integer between the specified minimum and maximum values (inclusive).
import { generateRandomNumber } from 'react-tesna-utils';
// Generate a random number between 1 and 10
const randomNum = generateRandomNumber(1, 10);
// Example output: 3
// Generate a random number between 100 and 200
const randomNumInRange = generateRandomNumber(100, 200);
// Example output: 142
getBase64
Converts an image or file (e.g., Blob
, File
) into a Base64 string representation.
img
(T
): The image or file (of type Blob
or File
) to be converted to a Base64 string. The type is generic, defaulting to Blob.callback
((url: string) => void
): A callback function that will be called with the Base64 string representation of the image once the conversion is complete.void
: This function does not return a value. It passes the Base64 string to the provided callback function.import { getBase64 } from 'react-tesna-utils';
// Example usage for an image file
const imageFile = document.querySelector('input[type="file"]')?.files?.[ 0 ];
if (imageFile) {
getBase64(imageFile, (base64Url) => {
console.log(base64Url); // The Base64 string of the image
});
}
getChunksFromString
Splits a string into an array of substrings, each of a specified chunk size.
str
(string
): The string to be split into chunks.chunkSize
(number
): The maximum size of each chunk.string[] | null
: An array of substrings split by the specified chunk size. If the string does not match the regular expression, it will return null
.import { getChunksFromString } from 'react-tesna-utils';
const longString = "This is a long string that needs to be chunked.";
const chunked = getChunksFromString(longString, 10);
console.log(chunked);
// Output: [ 'This is a ', 'long strin', 'g that ne', 'eds to be', ' chunked.' ]
str
is shorter than the chunkSize
, it will return the entire string as a single element in the array.null
, the function will return null
.isAllEnglishCharacters
Checks if the given string contains only English characters, spaces, digits, and punctuation.
input
(string
): The string to check.boolean
: true
if the input string contains only English characters (both uppercase and lowercase), spaces, digits, or punctuation. Otherwise, returns false.import { isAllEnglishCharacters } from 'react-tesna-utils';
const input1 = "Hello, World!";
const input2 = "مرحبا بالعالم";
console.log(isAllEnglishCharacters(input1)); // Output: true
console.log(isAllEnglishCharacters(input2)); // Output: false
/^[a-zA-Z\s\d\p{P}]+$/u
) to ensure that the string contains only English letters (both lowercase and uppercase), spaces,
digits,
and punctuation characters.false
if the string contains any non-English characters (such as Arabic, Chinese, etc.) or other symbols not allowed by the regex.\p{P}
.isAllPersianCharacters
Checks if the given string contains only Persian characters, spaces, digits, and punctuation.
input
(string
): The string to check.boolean
: true
if the input string contains only English characters (both uppercase and lowercase), spaces, digits, or punctuation. Otherwise, returns false.import { isAllPersianCharacters } from 'react-tesna-utils';
const input1 = "سلام دنیا!";
const input2 = "Hello World!";
console.log(isAllPersianCharacters(input1)); // Output: true
console.log(isAllPersianCharacters(input2)); // Output: false
/^[\u0600-\u06FF\s\d\p{P}]+$/u
) to ensure that the string contains only Persian characters (Unicode range \u0600-\u06FF
),
spaces, digits, and punctuation characters.false
if the string contains any non-Persian characters (such as English, Arabic, etc.) or other symbols not allowed by the regex.\p{P}
.isArrayEqual
Compares two arrays to determine if they are equal, taking into account both their size and content.
x
(unknown[]
): The first array to compare.y
(unknown[]
): The second array to compare.boolean
: true
if the arrays have the same size and identical elements (compared by value). Otherwise, returns false.import { isArrayEqual } from 'react-tesna-utils';
const array1 = [ 1, 2, 3 ];
const array2 = [ 1, 2, 3 ];
const array3 = [ 4, 5, 6 ];
console.log(isArrayEqual(array1, array2)); // Output: true
console.log(isArrayEqual(array1, array3)); // Output: false
This function uses lodash methods size, xorWith, and isEqual to compare the arrays:
size
: Ensures both arrays are of the same length.xorWith
: Compares the elements of both arrays and checks if any elements are different.isEqual
: Compares array elements by value, checking for deep equality.It returns true if the arrays have the same number of elements and all corresponding elements are equal by value.
isContainsEnglishCharacter
Checks if the given string contains at least one English character.
input
(string
): The string to check for English characters.boolean
: true
if the string contains at least one English character (either lowercase or uppercase). Otherwise, returns false
.import { isContainsEnglishCharacter } from 'react-tesna-utils';
const str1 = "Hello, world!";
const str2 = "مرحبا بالعالم";
console.log(isContainsEnglishCharacter(str1)); // Output: true
console.log(isContainsEnglishCharacter(str2)); // Output: false
/[a-zA-Z]/
to search for English alphabetic characters (both lowercase and uppercase).true
if the string contains at least one English letter and false
otherwise.isContainsPersianCharacter
Checks if the given string contains at least one Persian character.
input
(string
): The string to check for English characters.boolean
: true
if the string contains at least one English character (either lowercase or uppercase). Otherwise, returns false
.import { isContainsPersianCharacter } from 'react-tesna-utils';
const str1 = "سلام دنیا";
const str2 = "Hello World";
console.log(isContainsPersianCharacter(str1)); // Output: true
console.log(isContainsPersianCharacter(str2)); // Output: false
console.log(isContainsPersianCharacter(undefined)); // Output: false
/[\u0600-\u06FF]/
to search for Persian characters within the Unicode range for Persian script.true
if the string contains at least one Persian character and false
otherwise.isJson
Checks if the provided string is a valid JSON string.
str
(string
): The string to check if it's a valid JSON.boolean
: true
if the string is a valid JSON, otherwise false
.import { isJson } from 'react-tesna-utils';
const validJson = '{"name": "John", "age": 30}';
const invalidJson = '{name: John, age: 30}';
console.log(isJson(validJson)); // Output: true
console.log(isJson(invalidJson)); // Output: false
JSON.parse()
. If it successfully parses the string, it returns true
, indicating the string is valid JSON.
Otherwise,
it
catches the error and returns false
.isNumber
Checks if the provided value is a valid number.
val
(any
): The value to check if it is a number.boolean
: true
if the value is a valid number, otherwise false
.import { isNumber } from 'react-tesna-utils';
console.log(isNumber(123)); // Output: true
console.log(isNumber('123')); // Output: true
console.log(isNumber('abc')); // Output: false
console.log(isNumber(NaN)); // Output: false
console.log(isNumber(null)); // Output: false
parseFloat
to check if the value can be converted into a number, and it also checks for numeric values by subtracting zero (val - 0
).false
.isValidEmail
Validates if the provided string is a valid email address.
value
(string
): The email address to validate.boolean
: true
if the value is a valid email address, otherwise false
.import { isValidEmail } from 'react-tesna-utils';
console.log(isValidEmail('test@example.com')); // Output: true
console.log(isValidEmail('invalid-email.com')); // Output: false
console.log(isValidEmail('user@domain.co.uk')); // Output: true
console.log(isValidEmail('example@domain')); // Output: false
isValidNationalCode
Validates if the provided number or string is a valid Iranian national code (ID).
value
(number | string
): The national code (ID) to validate.boolean
: true
if the value is a valid Iranian national code, otherwise false
.import { isValidNationalCode } from 'react-tesna-utils';
console.log(isValidNationalCode('1234567890')); // Output: false (example invalid code)
console.log(isValidNationalCode('1234567891')); // Output: true (example valid code)
console.log(isValidNationalCode(9876543210)); // Output: true (example valid code)
toEnDigit
to ensure proper validation.removeEmptyKeys
Removes empty keys and values from an object or array. Empty keys are those with null
, undefined
, or empty string values, and empty objects are replaced by empty
objects.
obj
(AnyObject | AnyArray
): The object or array to process.AnyObject | AnyArray
: A new object or array with empty keys removed. Empty objects inside arrays are replaced by empty objects.import { removeEmptyKeys } from 'react-tesna-utils';
// Example with an object
const obj = {
name: 'John',
age: null,
address: {},
country: 'USA'
};
const cleanedObj = removeEmptyKeys(obj);
console.log(cleanedObj);
// Output: { name: 'John', country: 'USA' }
// Example with an array
const arr = [ {}, 'hello', { name: 'Alice' }, '' ];
const cleanedArr = removeEmptyKeys(arr);
console.log(cleanedArr);
// Output: [{}, 'hello', { name: 'Alice' }]
null
, undefined
, or an empty object.removeNullsFromArray
Removes all null
values from an object or array. This function recursively traverses the object or array and filters out null
values, applying the filtering to nested
structures as well.
obj
(any
): The object or array to process, which may contain null
values.any
: A new object or array with all null
values removed. If the input is an object, the properties with null
values will be removed. If the input is an array,
null
values are removed from the array.import { removeNullsFromArray } from 'react-tesna-utils';
// Example with an object
const obj = {
name: 'John',
age: null,
address: { city: 'New York', zip: null },
country: 'USA'
};
const cleanedObj = removeNullsFromArray(obj);
console.log(cleanedObj);
// Output: { name: 'John', address: { city: 'New York' }, country: 'USA' }
// Example with an array
const arr = [ null, 'hello', null, [ null, 'world' ], { key: null, value: 'test' } ];
const cleanedArr = removeNullsFromArray(arr);
console.log(cleanedArr);
// Output: ['hello', ['world'], { value: 'test' }]
undefined
, or an empty object.null
values, regardless of their position (whether in objects, arrays, or nested structures), will be removed.null
values are retained in the returned structure.truncatedMiddleText
Truncates a string by removing the middle portion and replacing it with a separator (...
). This function is useful for displaying shortened versions of longer texts
where only the start and end portions are needed.
text
(string
): The input string to be truncated.startLength
(number
, optional): The number of characters to retain from the start of the string. Default is 5
.endLength
(number
, optional): The number of characters to retain from the end of the string. Default is 15
..separator
(string
, optional): The separator to use in the middle of the truncated string. Default is ...
.string
: A truncated string with the middle portion replaced by the separator if the length exceeds the combined startLength
and endLength
.import { truncatedMiddleText } from 'react-tesna-utils';
// Example 1: Basic usage
const result1 = truncatedMiddleText({ text: 'This is a very long sentence that needs truncation.' });
console.log(result1);
// Output: 'This ...n.' (5 characters from the start and 15 characters from the end)
// Example 2: Custom start and end lengths
const result2 = truncatedMiddleText({
text: 'The quick brown fox jumps over the lazy dog.',
startLength: 3,
endLength: 4
});
console.log(result2);
// Output: 'The ...dog.' (3 characters from the start and 4 characters from the end)
// Example 3: Custom separator
const result3 = truncatedMiddleText({
text: 'A very long text example that needs truncation.',
separator: '***'
});
console.log(result3);
// Output: 'A v***tion.' (Default start and end lengths with custom separator)
text
is shorter than the combined lengths of startLength
and endLength
, the function returns the original text.text
is empty or undefined, it returns the text as is.wait
Creates a delay by returning a promise that resolves after a specified duration. This function is useful for adding pauses or delays in asynchronous code.
duration
(number
): The amount of time (in milliseconds) to wait before resolving the promise.Promise<void>
: A promise that resolves after the specified duration.import { wait } from 'react-tesna-utils';
// Example 1: Using wait for a delay in an async function
async function example() {
console.log('Start');
await wait(2000); // Wait for 2 seconds
console.log('End');
}
example();
// Output:
// Start
// (After 2 seconds)
// End
duration
is in milliseconds, so 1000
represents a 1-second delay.Promise
, making it useful for chaining with async/await
or .then()
for handling asynchronous flows.deepCompareAndRemove
This function compares two objects or arrays deeply. It removes keys from the first object (obj1
) if their values match in the second object (obj2
). If obj2
is not
provided, the function returns the entire obj1
. The function can handle nested objects and arrays.
obj1
: The main object or array to process.obj2
(optional): The reference object or array to compare against.obj1
based on the comparison with obj2
.import { deepCompareAndRemove } from 'react-tesna-utils';
const obj1 = {
name: "Alice",
age: 30,
address: {
city: "New York",
zip: 10001,
additional: {
info: "Apartment 12B",
details: null,
},
},
hobbies: [ "reading", "sports", "coding" ],
};
const obj2 = {
name: "Alice",
address: {
city: "New York",
additional: {
info: "Apartment 12B",
},
},
hobbies: [ "reading", "sports" ],
};
const result = deepCompareAndRemove(obj1, obj2);
console.log(result);
/*
{
age: 30,
address: {
zip: 10001,
additional: {
details: null,
},
},
hobbies: ["coding"],
}
*/
obj1
matches the corresponding value in obj2
, the key is removed.This utility is helpful for scenarios where you need to filter out unchanged or duplicate data in hierarchical structures, such as processing configuration files or response data.
useCopy
The useCopy
custom hook simplifies copying text to the clipboard in a React application. It handles the logic for copying, loading states, and resetting the state after
a
delay.
isCopied
: A boolean
indicating whether the text has been successfully copied.isCopyLoading
: A boolean
indicating if the copying process is in progress.copyText
: A function that takes a string (text
) and attempts to copy it to the clipboard.import { useCopy } from 'react-tesna-utils';
const CopyExample = () => {
const { isCopied, isCopyLoading, copyText } = useCopy();
return (
<div>
<button
onClick={ () => copyText('Hello, World!') }
disabled={ isCopyLoading }
>
{ isCopyLoading ? 'Copying...' : isCopied ? 'Copied!' : 'Copy Text' }
</button>
</div>
);
};
export default CopyExample;
navigator.clipboard
API, which is supported in most modern browsers. If the Clipboard API is not supported, it logs an error to
the
console and returns false
.This utility is perfect for creating user-friendly interactions, such as "Copy to Clipboard" buttons.
FAQs
A versatile utility library featuring optimized functions for data manipulation, clipboard handling, text truncation, comparison, validation, and more. Designed for modern JavaScript and TypeScript projects with efficient and reusable solutions.
We found that react-tesna-utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.