Skip to main content

Helper

Helper utils are a collection of useful functions that can be used for walkerOS. They can be used as standardized building blocks for custom setups.

Utils are grouped into Core and  Web functions. While the core-helpers can be used in any environment, the web-helpers are are made for the browser.

Core

anonymizeIP

anonymizeIP(ip: string): string is used to anonymize IP addresses (v4) by masking the last octet with zeros. This is particularly useful in scenarios where you need to store or process IP addresses while maintaining user privacy.

assign

assign<T>(target: T, source: WalkerOS.AnyObject = {}, options?): T function merges two objects into a single one. It has a special behavior for array properties: when merging, it concatenates arrays from both the source and target objects, removing duplicate items in the process. This function is particularly useful for combining objects with complex structures, including nested arrays, ensuring that array data is effectively integrated without redundancy.

// Options
interface Assign {
merge?: boolean; // Merge array properties (default) instead of overriding them
shallow?: boolean; // Create a shallow copy (default) instead of updating the target object
extend?: boolean; // Extend the target with new properties (default) instead of only updating existing ones
}

const obj1 = { a: 1, b: [1, 2] };
const obj2 = { b: [2, 3], c: 3 };

assign(obj1, obj2); // Returns { a: 1, b: [1, 2, 3], c: 3 }
assign(obj1, obj2, { merge: false }); // Returns { a: 1, b: [2, 3], c: 3 }
assign(obj1, obj2, { shallow: false }); // updates obj1 to { a: 1, b: [2, 3], c: 3 }
assign(obj1, obj2, { extend: false }); // Returns { a: 1, b: [1, 2, 3] }

Use assign to merge configurations or state-objects or events, particularly when dealing with array properties that should be concatenated without duplicates.

byPath

getByPath

getByPath(event: unknown, key: string, i=0): unknown allows accessing properties in an object with a string path. It supports using a wildcard _ to iterate through array elements. If the specified path does not exist, the function returns undefined, ensuring safe access to nested properties.

getByPath({ data: { id: 'wow' } }, 'data.id');
// Returns "wow"

Use the wildcard character _ and i for dynamic access on arrays, like "nested._.id"

getByPath({ nested: [1, 2, { id: 'impressive' }] }, 'nested._.id', 2);
// Returns 'impressive'

It's created to access values from an event by using the string-dot notation.

setByPath

setByPath(event: WalkerOS.Event, key: string, value: unknown): WalkerOS.Event updates the event object by setting the given value at the specified dot-separated key path, mutating the original event object in place.

setByPath(event, 'data.id', 'wow');
// Updates and returns the event object with { data: { id: 'wow' } }

castValue

castValue(value: unknown): WalkerOS.PropertyType function converts string values to their respective data types like number or boolean. This is useful when dealing with values that are inherently strings, such as those from query parameters or data-attributes, and need to be utilized in their correct data type.

const num = castValue('123'); // Converts to 123 (number)
const bool = castValue('true'); // Converts to true (boolean)

The function simplifies the process of data type conversion, ensuring that string inputs are appropriately processed for further use in various logic flows.

clone

clone<T>(org: T): T is designed for deep cloning by making a recursive copy of the org input (e.g. object or array), preserving the structure and contents of the original object. clone creates an exact, deep copy of an object or array that's independent of the original with no shared references to prevent mutations.

const org = { foo: true, b: ['foo'] };
const cloned = clone(org);
org.foo = false;
org.b.push('bar');
// org: { foo: false, b: ['foo', 'bar'] }
// cloned: { foo: true, b: ['foo'] }

getId

getId(length=6): string function generates a random alphanumeric string of a specified length.

getId(); // Returns a random string, e.g., 'a1b2c3'
getId(10); // Returns a random string of 10 characters, e.g., 'a1b2c3d4e5'

This function is particularly useful for scenarios where unique identifiers are needed, such as dynamically generated element IDs, unique keys for list items in rendering, or temporary identifiers.

getMappingValue

getMappingValue(event: WalkerOS.Event, mapping: WalkerOS.MappingValue, options?: Mapping.Options): WalkerOS.Property | undefined reads the value from an event based on the mapping configuration. It is used by destinations to transform walkerOS events into another required format.

interface Options {
instance?: WalkerOS.Instance;
props?: unknown;
}

getMarketingParameters

getMarketingParameters(url: string, custom={}): WalkerOS.Properties extracts marketing-related parameters, such as UTM parameters, from URLs. This is useful in scenarios where you need to analyze the effectiveness of marketing campaigns by identifying sources, mediums, campaigns, etc., from the URL query parameters.

getMarketingParameters('https://example.com/?utm_source=docs&gclid=xxx');
// Returns { source: "docs", gclid: "xxx", clickId: "gclid" }

getMarketingParameters('https://example.com/?utm_custom=value&partner=abc', {
utm_custom: 'custom',
partner: 'partnerId',
});
// Returns { custom: 'value' }

Add custom parameters to parse more values from the url like ?utm_custom=123 with { utm_custom: "custom" } to get { custom: "123" }. If the value is clickId an additional clickId parameter pointing to the key is added.

getMarketingParameters('https://example.com/?partner=abc', {
partner: 'clickId',
});
// Returns { partner: "abc", clickId: "partner" }

This function facilitates the easy retrieval of marketing data, aiding in campaign tracking and analysis.

UserAgent

A collection of functions to extract information from the user agent string.

parseUserAgent(userAgent?: string): WalkerOS.User combines all userAgent-functions to extract available information to return an object with the following properties:

// All keys are optional parts of the WalkerOS.User object
interface User {
userAgent: string; // Used UserAgent string
browser: string; // Browser name
browserVersion: string; // Browser version
os: string; // Operating system
osVersion: string; // Operating system version
deviceType: string; // Device type
}

getBrowser

getBrowser(userAgent: string): string | undefined extracts the browser name and returns one of Chrome, Firefox, Safari, Edge, IE, or undefined.

getBrowserVersion

getBrowserVersion(userAgent: string): string | undefined extracts the browser's version.

getOS

getOS(userAgent: string): string | undefined extracts the operating system, and returns one of Windows, macOS, iOS, Android, Linux, or undefined.

getOSVersion

getOSVersion(userAgent: string): string | undefined extracts the operating system's version.

getDeviceType

getDeviceType(userAgent: string): string | undefined is a lean implementation to extract the device type, which is either Desktop, Tablet, or Mobile.

Invocations

The debounce and throttle functions are both ways to batch invocations, designed to optimize function execution frequency. They're used for performance optimizations or cost reduction, these functions create batches of previously individual calls in two different ways.

debounce

debounce(fn: Function, wait=1000) delays a function's execution until a specified time has elapsed since the last time it was invoked. This is ideal for use cases like search input handling, where you don't want the function to fire on every keystroke.

debounce(console.log)('called'); // Executes only after 1000ms of inactivity

const debouncedLog = debounce(() => console.log('Debounced'), 500);
debouncedLog(); // Executes only after 500ms of inactivity

throttle

Limits the execution of a function to no more than once every specified number of milliseconds. It's beneficial for situations like scroll events where you want to limit how often an event handler is called.

const throttledLog = throttle(() => console.log('Throttled'), 500);
throttledLog(); // Executes at most every 500ms

isSameType

isSameType<T>(variable: unknown, type: T): variable is typeof type checks if two provided values are of the same data type. This function is essential in scenarios requiring type validation, ensuring consistency and preventing errors due to type mismatches.

isSameType(10, 20); // Returns true (both are numbers)
isSameType('hello', 5); // Returns false (different types)

This function helps in validating inputs, comparing variables, and ensuring data integrity by verifying that operations are performed on matching data types.

onLog

onLog(message: string, level: string) is a function designed for consistent and customizable logging across your application. It allows you to log messages with with a verbose option, aiding in better monitoring and debugging of your code.

onLog('Silent'); // Won't log anything
onLog('Curious', true); // Logs a message

This function is for maintaining a standardized logging format is crucial. I

Request

requestToURL

requestToData

sessionStart

As this is a more complex util learn more about it on the Session page.

Storage

As this is are more complex utils learn more about them on the Storage page.

throwError

throwError(message: string) is used to throw custom errors with a specific message. It's particularly useful in scenarios where standard error handling needs to be customized or more descriptive error messages are required for debugging.

throwError('Broken'); // Throws an error with the message 'Broken'

This function enhances error management by allowing you to provide clear, context-specific error messages, aiding in the debugging process and improving code maintainability.

trim

trim(str: string): string is designed to remove whitespace from both ends of a string. This is useful for cleaning up user input or values from data-attributes.

trim('  Moin  '); // Returns 'Moin' without leading or trailing spaces

Using trim ensures that strings are processed in a consistent format, which is essential for accurate data handling and user input validation.

try-catch

These functions are ideal to ensure that the application remains robust and error-free, especially when dealing with uncertain or risky operations. By providing a fallback mechanism, tryCatch and tryCatchAsync enhances the stability and reliability of code.

tryCatch

tryCatch(tryFn: Function, catchFn: Function) is a higher-order function designed to handle errors gracefully in JavaScript. It takes two functions as arguments: tryFn, which is the function to be executed, and catchFn, which is the function to be executed if tryFn throws an error.

const safeParse = tryCatch(JSON.parse, () => ({}));
safeParse('{"valid": "json"}'); // Successfully parses JSON
safeParse('invalid json'); // Returns {} instead of throwing an error

tryCatchAsync

tryCatchAsync(tryFn: Function, catchFn: Function) is similar to tryCatch but tailored for asynchronous operations. It wraps an async function (tryFn) and a fallback (catchFn) for handling errors in async processes.

const safeCall = tryCatchAsync(
() => asyncFnThatMightFail(),
() => ({ error: 'Bad luck' }),
);
safeCall().then(console.log);

This function ensures your async operations are robust, providing a way to handle errors gracefully without disrupting the application flow.

useHooks

As this is a more complex util learn more about it on the Hooks page.

Node

getHashNode

async getHashNode(str: string, length?: number): Promise<string> generates a hash value from a string, usually used to anonymize or fingerprinting. To create a string concatenate all values. Use length to limit the output.

await getHashNode('' + userAgent + language + domain + dayOfMonth, 16);
// Return a 16 character hash, like 47e0bdd10f04ef13

sendNode

async sendNode(url: string, data?: SendDataValue, options: SendNodeOptions = {}): Promise<SendResponse> sends data to a specified url using the official Node.js HTTP/HTTPS modules. This function is useful for scenarios where you need to send data to a server or API endpoint from a Node.js environment.

interface SendNodeOptions {
headers?: SendHeaders; // Custom headers to be sent with the request
method?: string; // HTTP method to be used for the request (default: POST)
timeout?: number; // Request timeout in milliseconds (default: 5000)
}

interface SendResponse {
ok: boolean; // Indicates if the request was successful
data?: unknown; // (Parsed) response data (if available)
error?: string; // Error message (if request failed)
}

Web

Browser

These functions are designed to provide mode detailed information about the user's browser settings.

Note: Accessing this information might require a user's consent

getLanguage

getLanguage(navigatorRef: Navigator): string | undefined returns the user's preferred language.

getTimezone

getTimezone(): string | undefined reads the user's timezone from Intl object.

getScreenSize

getScreenSize(windowRef: Window): string returns the windows's screen size.

getAttribute

getAttribute(element: HTMLElement, attribute: string): string is designed for retrieving the value of a specified attribute from a given DOM element. This utility is especially handy when you need to extract data dynamically from elements on a webpage, such as reading data attributes, class names, or IDs.

const element = document.body;
const value = getAttribute(element, 'data-elb');
// Retrieves the value of 'data-elb' from the documents body

This function simplifies the process of interacting with the DOM by providing an easy and direct way to access element attributes.

getHashWeb

async getHashWeb(str: string, length?: number): Promise<string> generates a hash value from a string, usually used to anonymize or fingerprinting. To create a string concatenate all values. Use length to limit the output.

await getHashWeb('' + userAgent + language + domain + dayOfMonth, 16);
// Return a 16 character hash, like 47e0bdd10f04ef13

isVisible

isVisible(element: HTMLElement): boolean checks if a given HTML element is visible on the page from a users perspective.

isVisible(document.getElementById('promotion'));
// Returns true if 'promotion' is visible

sendWeb

async sendWeb(url: string, data?: SendDataValue, options: SendWebOptionsDynamic { transport: 'fetch' }): SendWebReturn sends data to a specified url using the browser's native APIs. This function is useful for scenarios where you need to send data to a server or API endpoint from a web environment. It supports sending data via fetch, beacon, or XHR.

type SendWebTransport = 'fetch' | 'beacon' | 'xhr';

interface SendWebOptions {
headers?: SendHeaders; // Custom headers to be sent with the request
transport?: SendWebTransport; // Transport method to be used for the request (default: fetch)
method?: string; // HTTP method to be used for the request (default: POST)
}

interface SendResponse {
ok: boolean; // Indicates if the request was successful
data?: unknown; // (Parsed) response data (if available)
error?: string; // Error message (if request failed)
}

sendWeb calls one of the following functions based on the transport option.

sendWebAsBeacon

sendWebAsBeacon(url: string, data?: SendDataValue): SendResponse sends data to a specified url using the browser's Beacon API. The Beacon API is designed for sending small amounts of data to a server with minimal impact on the user's experience. It is typically used for sending analytics data and best for small, non-critical data payloads. It ensures data is sent even if the page is being closed.

sendWebAsFetch

async sendWebAsFetch(url: string, data?: SendDataValue, options: SendWebOptionsFetch = {}): Promise<SendResponse> sends data to a specified url using the browser's Fetch API. It provides a modern way to make more powerful and flexible network requests than older XHR method. It can be used for both simple and complex data transactions and returns a promise. Additionally, it supports the credentials and noCors options.

interface SendWebOptionsFetch extends SendWebOptions {
credentials?: 'omit' | 'same-origin' | 'include'; // Add credentials option
noCors?: boolean; // Add noCors option for fetch transport
}

sendWebAsXhr

sendWebAsXhr(url: string, data?: SendDataValue, options: SendWebOptions = {}): SendResponse sends data to a specified url using the browser's older XMLHttpRequest API. It's implemented to make synchronous requests only. It's a reliable method for sending and receiving data from a server.

info

If you need professional support with your walkerOS implementation, check out our services.