Skip to main content

General Helpers

Comprehensive collection of general utility functions for common operations in the WorkPayCore frontend application.

Validation Functions

isNull(variable)

Checks if a variable is null, undefined, or represents empty values.

Parameters:

  • variable (any): The variable to check

Returns:

  • boolean: True if the variable is considered null/empty

Example:

import { isNull } from '@/utils/helpers';

isNull(null); // Returns: true
isNull(undefined); // Returns: true
isNull(''); // Returns: true
isNull('null'); // Returns: true
isNull('NULL'); // Returns: true
isNull('undefined'); // Returns: true
isNull(0); // Returns: false
isNull(false); // Returns: false
isNull('hello'); // Returns: false

Use Cases:

  • Form field validation
  • API response checking
  • Safe data processing
  • Preventing null reference errors

oneItemIsNullish(...args)

Checks if any of the provided arguments is nullish (null or undefined).

Parameters:

  • ...args (any[]): Variable number of arguments to check

Returns:

  • boolean: True if at least one argument is nullish

Example:

import { oneItemIsNullish } from '@/utils/helpers';

oneItemIsNullish('hello', 'world'); // Returns: false
oneItemIsNullish('hello', null, 'world'); // Returns: true
oneItemIsNullish(undefined, 'test'); // Returns: true
oneItemIsNullish(1, 2, 3); // Returns: false
oneItemIsNullish(); // Throws: TypeError

Use Cases:

  • Multi-field validation
  • Required parameter checking
  • Form submission validation
  • API payload validation

Encoding/Decoding Functions

WPBTOA(str)

Creates a base-64 encoded ASCII string from a String object.

Parameters:

  • str (string): The string to be encoded

Returns:

  • string: Base64 encoded string

Example:

import { WPBTOA } from '@/utils/helpers';

const encoded = WPBTOA('Hello World');
console.log(encoded); // Returns: 'SGVsbG8gV29ybGQ='

const data = WPBTOA('user:password');
console.log(data); // Returns: 'dXNlcjpwYXNzd29yZA=='

Use Cases:

  • Basic authentication headers
  • Data encoding for transmission
  • Simple obfuscation
  • API token preparation

WPATOB(str)

Decodes a string of data which has been encoded using base-64 encoding.

Parameters:

  • str (string): The base-64 encoded string to be decoded

Returns:

  • string: Decoded string

Example:

import { WPATOB } from '@/utils/helpers';

const decoded = WPATOB('SGVsbG8gV29ybGQ=');
console.log(decoded); // Returns: 'Hello World'

const credentials = WPATOB('dXNlcjpwYXNzd29yZA==');
console.log(credentials); // Returns: 'user:password'

Use Cases:

  • Decoding API responses
  • Processing encoded data
  • Credential extraction
  • Data retrieval

Array Utilities

containsValue(list, value)

Checks if an array contains a specific value.

Parameters:

  • list (array): The array to search in
  • value (any): The value to search for

Returns:

  • boolean: True if the value is found in the array

Example:

import { containsValue } from '@/utils/helpers';

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];

containsValue(numbers, 3); // Returns: true
containsValue(numbers, 6); // Returns: false
containsValue(fruits, 'apple'); // Returns: true
containsValue(fruits, 'grape'); // Returns: false

Use Cases:

  • Permission checking
  • Feature availability
  • Filter validation
  • Data existence checks

Type Conversion Functions

convertZeroOneToTrueFalse(value)

Converts numeric or string values (0, 1, '0', '1', 'true') to boolean.

Parameters:

  • value (number | string): The value to convert

Returns:

  • boolean: Converted boolean value

Example:

import { convertZeroOneToTrueFalse } from '@/utils/helpers';

convertZeroOneToTrueFalse(1); // Returns: true
convertZeroOneToTrueFalse('1'); // Returns: true
convertZeroOneToTrueFalse('true'); // Returns: true
convertZeroOneToTrueFalse(0); // Returns: false
convertZeroOneToTrueFalse('0'); // Returns: false
convertZeroOneToTrueFalse('false'); // Returns: false

Use Cases:

  • Database boolean conversion
  • API response processing
  • Form data normalization
  • Configuration parsing

convertTrueFalseToZeroOne(value)

Converts a boolean value to numeric representation (1 for true, 0 for false).

Parameters:

  • value (boolean): The boolean value to convert

Returns:

  • number: 1 for true, 0 for false

Example:

import { convertTrueFalseToZeroOne } from '@/utils/helpers';

convertTrueFalseToZeroOne(true); // Returns: 1
convertTrueFalseToZeroOne(false); // Returns: 0

// Throws error for non-boolean input
convertTrueFalseToZeroOne('true'); // Throws: Error

Use Cases:

  • Database storage preparation
  • API payload formatting
  • Numeric calculations with booleans
  • Legacy system integration

openInNewTab(url, params?)

Opens a URL in a new browser tab with optional query parameters.

Parameters:

  • url (string): The URL to open
  • params (object, optional): Query parameters to append

Returns:

  • void: No return value

Example:

import { openInNewTab } from '@/utils/helpers';

// Simple URL
openInNewTab('https://example.com');

// URL with parameters
openInNewTab('https://example.com/search', {
query: 'workpay',
page: 1,
limit: 10,
});
// Opens: https://example.com/search?query=workpay&page=1&limit=10&

// Open report in new tab
openInNewTab('/reports/payroll', {
month: '2024-01',
department: 'engineering',
});

Use Cases:

  • External link handling
  • Report generation
  • Documentation links
  • Help system navigation

Utility Functions

debounceFunction(func, timeout?)

Creates a debounced version of a function that delays execution until after a specified timeout.

Parameters:

  • func (function): The function to debounce
  • timeout (number, optional): Delay in milliseconds (default: 300)

Returns:

  • function: Debounced function

Example:

import { debounceFunction } from '@/utils/helpers';

// Debounced search function
const debouncedSearch = debounceFunction(query => {
console.log('Searching for:', query);
// API call here
}, 500);

// Usage in input handler
const handleInputChange = e => {
debouncedSearch(e.target.value);
};

// Multiple rapid calls will only execute the last one after 500ms
debouncedSearch('a');
debouncedSearch('ab');
debouncedSearch('abc'); // Only this will execute after 500ms

Use Cases:

  • Search input optimization
  • API call throttling
  • Resize event handling
  • Auto-save functionality

clearLocalStorageAuthKeys()

Clears all authentication-related localStorage keys.

Parameters:

  • None

Returns:

  • void: No return value

Example:

import { clearLocalStorageAuthKeys } from '@/utils/helpers';

// On logout
const handleLogout = () => {
clearLocalStorageAuthKeys();
// Redirect to login
window.location.href = '/login';
};

// On authentication error
const handleAuthError = () => {
clearLocalStorageAuthKeys();
showErrorMessage('Session expired. Please login again.');
};

Clears these keys:

  • AUTH_SWITCHED_COMPANY_ID_KEY
  • AUTH_HEAD_OFFICE_ID_KEY
  • AUTH_ROLE_KEY
  • SWITCHED_COUNTRY_KEY
  • AUTH_SWITCHED_COMPANY
  • IS_ONBOARDING_KEY
  • CLIENT_ONBOARDING_KEY

Use Cases:

  • User logout
  • Session cleanup
  • Authentication reset
  • Error recovery

File Utilities

getFileExtension(url)

Extracts the file extension from a given URL.

Parameters:

  • url (string): The URL to extract extension from

Returns:

  • string | null: The file extension or null if not found

Example:

import { getFileExtension } from '@/utils/helpers';

getFileExtension('https://example.com/document.pdf');
// Returns: 'pdf'

getFileExtension('https://example.com/image.jpg?size=large');
// Returns: 'jpg'

getFileExtension('https://example.com/file');
// Returns: null

getFileExtension('invalid-url');
// Returns: null (logs error)

Use Cases:

  • File type validation
  • Icon selection
  • Upload restrictions
  • File categorization

Advanced Usage Examples

Form Validation Helper

import { isNull, oneItemIsNullish } from '@/utils/helpers';

const validateForm = formData => {
const errors = {};

// Check required fields
if (oneItemIsNullish(formData.firstName, formData.lastName, formData.email)) {
errors.required = 'All required fields must be filled';
}

// Check individual fields
if (isNull(formData.email)) {
errors.email = 'Email is required';
}

return {
isValid: Object.keys(errors).length === 0,
errors,
};
};

Safe Data Processing

import { isNull, convertZeroOneToTrueFalse } from '@/utils/helpers';

const processApiResponse = data => {
const processed = {};

// Safe value extraction
processed.name = isNull(data.name) ? 'Unknown' : data.name;
processed.isActive = convertZeroOneToTrueFalse(data.status);
processed.email = isNull(data.email) ? null : data.email.toLowerCase();

return processed;
};

Authentication Helper

import { WPBTOA, WPATOB, clearLocalStorageAuthKeys } from '@/utils/helpers';

class AuthHelper {
static encodeCredentials(username, password) {
return WPBTOA(`${username}:${password}`);
}

static decodeCredentials(encodedString) {
const decoded = WPATOB(encodedString);
const [username, password] = decoded.split(':');
return { username, password };
}

static logout() {
clearLocalStorageAuthKeys();
// Additional cleanup
}
}

Enhanced Search with Debounce

import { debounceFunction, isNull } from '@/utils/helpers';

const useSearch = searchFunction => {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);

const debouncedSearch = useMemo(
() =>
debounceFunction(async searchQuery => {
if (isNull(searchQuery)) {
setResults([]);
return;
}

setLoading(true);
try {
const searchResults = await searchFunction(searchQuery);
setResults(searchResults);
} catch (error) {
console.error('Search failed:', error);
setResults([]);
} finally {
setLoading(false);
}
}, 300),
[searchFunction],
);

useEffect(() => {
debouncedSearch(query);
}, [query, debouncedSearch]);

return { query, setQuery, results, loading };
};

Constants and Configurations

Health Scheme Values

// Kenya health scheme options
export const nhif = 'nhif'; // National Health Insurance Fund
export const shif = 'shif'; // Social Health Insurance Fund

API Configuration

// API base URL from environment
export const API_URL = import.meta.env.VITE_API_HOST_V2;

Best Practices

  1. Input Validation: Always validate inputs before processing
  2. Error Handling: Use try-catch blocks with encoding/decoding functions
  3. Type Safety: Use TypeScript for better type checking
  4. Performance: Use debouncing for expensive operations
  5. Security: Never encode sensitive data in production
  6. Cleanup: Always clear sensitive data on logout

Performance Considerations

  • Debouncing: Use appropriate timeouts for different use cases
  • Memory Management: Clear localStorage keys when needed
  • URL Parsing: Handle invalid URLs gracefully
  • Array Operations: Consider performance for large arrays


TypeScript Definitions

export function isNull(variable: any): boolean;
export function oneItemIsNullish(...args: any[]): boolean;
export function WPBTOA(str: string): string;
export function WPATOB(str: string): string;
export function containsValue(list: any[], value: any): boolean;
export function convertZeroOneToTrueFalse(value: number | string): boolean;
export function convertTrueFalseToZeroOne(value: boolean): number;
export function openInNewTab(url: string, params?: Record<string, any>): void;
export function debounceFunction(func: Function, timeout?: number): Function;
export function clearLocalStorageAuthKeys(): void;
export function getFileExtension(url: string): string | null;

Error Handling

All functions include proper error handling:

  • Type validation: Functions throw TypeError for invalid argument counts
  • URL parsing: getFileExtension logs errors for invalid URLs
  • Encoding errors: WPBTOA/WPATOB handle encoding failures gracefully
  • Null safety: Functions handle null/undefined inputs safely