Skip to main content
Ask your AI

Core utilities

Core utilities are platform-agnostic functions that work in every walkerOS environment, for data manipulation, validation, mapping, and more.

Installation​

Import the core utilities directly from the @walkeros/core package:

import { assign, anonymizeIP, getMappingValue } from '@walkeros/core';

Data manipulation​

assign​

assign<T, U>(target: T, source: U, options?): T & U merges two objects. When merging, it concatenates arrays from both objects and removes duplicates.

interface AssignOptions {
  merge?: boolean; // Merge array properties (default: true)
  shallow?: boolean; // Create shallow copy (default: true)
  extend?: boolean; // Extend with new properties (default: true)
}

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 }

Path operations​

getByPath​

getByPath(object: unknown, path: string, defaultValue?: unknown): unknown accesses nested properties using dot notation. Supports wildcard * for array iteration.

getByPath({ data: { id: 'wow' } }, 'data.id'); // Returns "wow"
getByPath({ nested: [1, 2, { id: 'cool' }] }, 'nested.*.id'); // Returns [undefined, undefined, 'cool']
getByPath({ arr: ['foo', 'bar'] }, 'arr.1'); // Returns "bar"

setByPath​

setByPath<T>(object: T, path: string, value: unknown, options?: { mutable?: boolean }): T sets nested values using dot notation, returning a new object with the updated value (with mutable: true, it changes object itself). Setting undefined removes the key.

const updatedEvent = setByPath(event, 'data.id', 'new-value');
// Returns a new event with data.id set to 'new-value'

clone​

clone<T>(original: T): T creates a deep copy of objects/arrays with circular reference handling.

const original = { foo: true, arr: ['a', 'b'] };
const cloned = clone(original);
original.foo = false; // cloned.foo remains true

castValue​

castValue(value: unknown): WalkerOS.PropertyType converts string values to appropriate types (number, boolean).

castValue('123'); // Returns 123 (number)
castValue('true'); // Returns true (boolean)
castValue('hello'); // Returns 'hello' (unchanged)

Privacy and security​

anonymizeIP​

anonymizeIP(ip: string): string anonymizes an IP address: an IPv4 address keeps its first three octets and the last becomes 0, an IPv6 address keeps its first 48 bits. An invalid address returns an empty string.

anonymizeIP('192.168.1.100'); // Returns '192.168.1.0'
anonymizeIP('2001:db8::1'); // Returns '2001:db8:0::'

Random IDs​

getId(length?: number, charset?: string): string generates random identifier strings from the platform's secure random source, falling back to Math.random when none is reachable. Defaults to a 6-character id from 0-9a-z; pass charset to restrict the allowed characters.

getId(); // Returns random 6-char string like 'a1b2c3'
getId(10); // Returns 10-character alphanumeric string
getId(5, 'abcdefghijklmnopqrstuvwxyz'); // Lowercase letters only

Event processing​

getMappingValue​

getMappingValue(event: WalkerOS.Event, mapping: Mapping.Data, context: Mapping.ValueContext): Promise<WalkerOS.Property | undefined> extracts values from events using

mapping configurations. The context requires the running collector: inside a step, take it from the step's context; elsewhere, use the one startFlow returns.

import { startFlow } from '@walkeros/collector';
import { getMappingValue } from '@walkeros/core';

const { collector } = await startFlow();
const event = {
  name: 'order complete',
  data: { id: '0rd3r1d' },
  nested: [
    { entity: 'product', data: { id: 'ers', name: 'Everyday Ruck Snack' } },
    { entity: 'gift', data: { name: 'Surprise' } },
  ],
};

// Simple path mapping
await getMappingValue(event, 'data.id', { collector }); // '0rd3r1d'

// Complex mapping with conditions and loops
const mapping = {
  map: {
    orderId: 'data.id',
    products: {
      loop: [
        'nested',
        {
          condition: (entity) => entity.entity === 'product',
          map: { id: 'data.id', name: 'data.name' },
        },
      ],
    },
  },
};
await getMappingValue(event, mapping, { collector });
// { orderId: '0rd3r1d', products: [{ id: 'ers', name: 'Everyday Ruck Snack' }] }

getMappingEvent​

getMappingEvent(event: WalkerOS.PartialEvent, mapping?: Mapping.Rules, collector?: Collector.Instance): Promise<Mapping.Result> finds the appropriate mapping rule for an event and returns it as eventMapping, with the matched mappingKey.

Marketing and analytics​

getMarketingParameters​

getMarketingParameters(url: URL, custom?: MarketingParameters, clickIds?: ClickIdEntry[]): WalkerOS.Properties extracts UTM and click ID parameters from URLs.

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

// With custom parameters
getMarketingParameters(url, { utm_custom: 'custom', partner: 'partnerId' });

Type validation​

Type checkers​

Type checking functions:

  • isString(value), isNumber(value), isBoolean(value)
  • isArray(value), isObject(value), isFunction(value)
  • isDefined(value), isSameType(a, b)
  • isPropertyType(value) - Checks if value is valid walkerOS property: a string, number, boolean, null or undefined, or an object or array of them

Property utilities​

  • castToProperty(value) - Returns the value when it is a valid property, otherwise undefined. As in mapping, a value that is or contains null is undefined
  • filterValues(value) - Copies only valid property values: it keeps null, turns a date into its timestamp in milliseconds, and leaves out everything else (functions, DOM elements, undefined, NaN, symbols, objects such as Map, keys whose getter throws and __proto__ keys). In a value without a cycle, an object referenced twice is kept twice, as JSON keeps it. Once a cycle is found, the back-reference and every later repeated reference in that call are left out

Request handling​

requestToData​

requestToData(parameter: unknown): WalkerOS.AnyObject | undefined converts query strings to JavaScript objects with type casting.

requestToData('a=1&b=true&c=hello&arr[0]=x&arr[1]=y');
// Returns { a: 1, b: true, c: 'hello', arr: ['x', 'y'] }

requestToParameter​

requestToParameter(data: WalkerOS.AnyObject): string converts objects to URL-encoded query strings.

requestToParameter({ a: 1, b: true, arr: ['x', 'y'] });
// Returns 'a=1&b=true&arr%5B0%5D=x&arr%5B1%5D=y'

User agent parsing​

parseUserAgent​

parseUserAgent(userAgent?: string): WalkerOS.User extracts browser, OS, and device information.

parseUserAgent(navigator.userAgent);
// Returns { userAgent: '...', browser: 'Chrome', browserVersion: '91', os: 'Windows', osVersion: '10.0', deviceType: 'Desktop' }

Individual functions are also available:

  • getBrowser(userAgent) - Returns browser name
  • getBrowserVersion(userAgent) - Returns browser version
  • getOS(userAgent) - Returns operating system
  • getOSVersion(userAgent) - Returns OS version
  • getDeviceType(userAgent) - Returns 'Desktop', 'Tablet', or 'Mobile'

Error handling​

tryCatch​

tryCatch(tryFn: Function, catchFn?: Function, finallyFn?: Function) wraps functions with error handling. Without catchFn, the wrapped function returns undefined when tryFn throws.

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

tryCatchAsync​

tryCatchAsync(tryFn: Function, catchFn?: Function, finallyFn?: Function) for async operations.

const safeAsyncCall = tryCatchAsync(
  () => fetchUserData(),
  (error) => ({ error: 'Failed to load user' }),
);

Performance optimization​

debounce​

debounce(fn: Function, wait?: number, immediate?: boolean) delays function execution until after the wait time (default 1000 ms).

const debouncedSearch = debounce(searchFunction, 300);
// Only executes after 300ms of inactivity

throttle​

throttle(fn: Function, wait?: number) limits function execution frequency (default 1000 ms). Calls inside the wait time are dropped.

const throttledScroll = throttle(scrollHandler, 100);
// Executes at most every 100ms

Utilities​

trim​

trim(str: string): string removes whitespace and surrounding single quotes from a string.

throwError​

throwError(error: unknown): never throws an Error with the value as its message.

For logging, see Logger.

For platform-specific utilities, see:

💡 Need implementation support?
elbwalker offers hands-on support: setup review, measurement planning, destination mapping, and live troubleshooting. Book a 2-hour session (€399)