Methods
Overview
Rebuy utilities provide helper functions for common operations including money formatting, product data manipulation, object handling, and more. All utilities are available on the global Rebuy.util namespace.
const util = window.Rebuy.util;
Quick Reference
| Category |
Methods |
| Formatting |
formatMoney, formatNumber, numberWithCommas, amountToCents, handlize |
| Products |
getStaticProducts, findLowestPricedVariant, findVariantBasedOnOptions, isBundleProduct, productImage |
| Discounts |
calculateDiscount |
| Objects |
deepCopy, extend |
| URLs |
getLocation, generateCartShareUrl |
| Clipboard |
copyToClipboard |
| Misc |
debounce, filterArray, isRebuyItem, randomRange, timestamp, wait |
amountToCents
Converts a decimal amount to cents (integer).
util.amountToCents(amount);
Parameters
amount · number | string · Required
- The amount to convert.
Returns
number - The amount in cents.
Example
Rebuy.util.amountToCents(159.59);
// Output: 15959
Rebuy.util.amountToCents("24.99");
// Output: 2499
Formats a cent value as a currency string wrapped in a <span> element.
util.formatMoney(cents, format);
Parameters
cents · number · Required
- The amount in cents.
format · string · Default: shop's money format
- Custom format string using Shopify's money format syntax.
Returns
string - HTML span element with formatted money.
Example
Rebuy.util.formatMoney(1299);
// Output: '<span class="money">$12.99</span>'
Rebuy.util.formatMoney(2499, "${{amount}}");
// Output: '<span class="money">$24.99</span>'
Formats a number with thousands separators and decimal places.
util.formatNumber(number, decimal_count, thousands_separator, decimal_separator);
Parameters
number · number | string · Required
- The number to format.
decimal_count · number · Default: 2
- Number of decimal places.
thousands_separator · string · Default: ","
- Character for thousands separation.
decimal_separator · string · Default: "."
- Character for decimal point.
Returns
string - The formatted number string.
Example
Rebuy.util.formatNumber(1562, 2, ",", ".");
// Output: '1,562.00'
Rebuy.util.formatNumber(99999.5, 2, " ", ",");
// Output: '99 999,50'
numberWithCommas
Formats a number with comma separators.
util.numberWithCommas(num);
Parameters
num · number · Required
- The number to format.
Returns
string - The formatted number with commas.
Example
Rebuy.util.numberWithCommas(1563);
// Output: '1,563'
Rebuy.util.numberWithCommas(1000000);
// Output: '1,000,000'
handlize
Converts a string to a URL-safe handle (slug).
Parameters
str · string · Required
- The string to convert.
Returns
string - A lowercase, hyphenated handle.
Example
Rebuy.util.handlize("Performance Half Zip Pullover");
// Output: 'performance-half-zip-pullover'
Rebuy.util.handlize("Men's T-Shirt (Large)");
// Output: 'mens-tshirt-large'
Use Cases
- Creating URL slugs from product titles
- Generating CSS class names from dynamic content
- Matching product handles to Shopify handles
Products
getStaticProducts
Fetches product data from the Rebuy /products/static endpoint. Returns full Shopify product data with support for contextual pricing and filtering options.
await util.getStaticProducts(params);
Parameters
params · object
- Query parameters for the request.
| Property |
Type |
Description |
ids |
string[] |
Shopify product IDs to fetch |
handles |
string[] |
Shopify product handles to fetch |
shopify_product_ids |
string[] |
Product IDs to filter from results |
shopify_collection_id |
string |
Collection ID to filter products |
country_code |
string |
ISO country code for contextual pricing (e.g., 'US') |
metafields |
string |
Set to 'yes' to include product metafields |
limit |
string |
Number of results to return (default: 5) |
bust_cache |
string |
Set to 'yes' to force a fresh response |
Returns
Promise<object> - Response containing data array of product objects.
Example
// Fetch specific products by IDs
const response = await Rebuy.util.getStaticProducts({
ids: ['8234567890123', '8234567890456']
});
console.log(response.data);
// Output: [{ id: 8234567890123, title: 'Product 1', ... }, ...]
// Fetch products with contextual pricing for Canada
const caProducts = await Rebuy.util.getStaticProducts({
ids: ['8234567890123'],
country_code: 'CA',
metafields: 'yes'
});
// Fetch products from a collection
const collectionProducts = await Rebuy.util.getStaticProducts({
shopify_collection_id: '123456789012',
limit: '10'
});
Use Cases
- Loading product data for custom widgets
- Fetching product details for comparison features
- Getting contextual pricing for international customers
findLowestPricedVariant
Finds the variant with the lowest price from a product's variants array.
util.findLowestPricedVariant(product);
Parameters
product · object · Required
- A Rebuy product object containing a
variants array.
Returns
object - The variant object with the lowest price, or empty object if no variants.
Example
const product = {
title: "Classic T-Shirt",
variants: [
{ id: 1, title: "Small", price: "24.99" },
{ id: 2, title: "Medium", price: "24.99" },
{ id: 3, title: "Large", price: "29.99" }
]
};
const cheapestVariant = Rebuy.util.findLowestPricedVariant(product);
console.log(cheapestVariant);
// Output: { id: 1, title: "Small", price: "24.99" }
Use Cases
- Displaying "Starting at $X" pricing
- Auto-selecting the most affordable variant
- Price comparison features
findVariantBasedOnOptions
Finds a variant that matches the currently selected product options.
util.findVariantBasedOnOptions(product);
Parameters
product · object · Required
- A product object with
variants array and option1, option2, option3 properties set to the selected option values.
Returns
object | null - The matching variant object, or null if no match found.
Example
const product = {
option1: "Blue",
option2: "Medium",
option3: null,
variants: [
{ id: 1, option1: "Blue", option2: "Small", option3: null, price: "24.99" },
{ id: 2, option1: "Blue", option2: "Medium", option3: null, price: "24.99" },
{ id: 3, option1: "Red", option2: "Medium", option3: null, price: "24.99" }
]
};
const selectedVariant = Rebuy.util.findVariantBasedOnOptions(product);
console.log(selectedVariant);
// Output: { id: 2, option1: "Blue", option2: "Medium", option3: null, price: "24.99" }
Use Cases
- Custom variant selectors
- Syncing variant selection across multiple option dropdowns
- Programmatic variant selection
isBundleProduct
Checks whether a cart item is a Shopify bundle product.
util.isBundleProduct(item);
Parameters
item · object · Required
- A Shopify cart item object.
Returns
boolean - true if the item is a bundle product, false otherwise.
Example
document.addEventListener('rebuy:cart.ready', (event) => {
const cart = event.detail.cart;
cart.items.forEach(item => {
if (Rebuy.util.isBundleProduct(item)) {
console.log(`${item.title} is a bundle product`);
}
});
});
Notes
- Detects products created via Shopify's Bundles app
- Products using Cart Transform API with only a default variant are not considered bundles
productImage
Resizes a product image URL to a specific size.
util.productImage(product, size);
Parameters
product · object · Required
- A product or variant object with an image property.
size · string · Default: "medium"
- The desired image size (e.g.,
"small", "medium", "large", or pixel dimensions like "300x300").
Returns
string - The resized image URL.
Discounts
calculateDiscount
Calculates discounted pricing for a product based on discount options.
util.calculateDiscount(product, isCompareAtPrice, discountOptions);
Parameters
product · object · Required
- A product object with
selected_variant containing price information.
isCompareAtPrice · boolean · Required
- Whether to use the compare-at price as the baseline.
discountOptions · array
- Array of discount option objects with
discountType ('one-time' or 'subscription'), type ('percentage', 'fixed_amount', or 'price'), and amount.
Returns
object - Calculated discount information:
| Property |
Type |
Description |
compareAtPrice |
number |
Original/compare price |
discountedPrice |
number |
Final discounted price |
savingAmount |
number |
Amount saved (percentage or fixed) |
type |
string |
Discount type used |
shouldShowDiscountedPrice |
boolean |
Whether to display the discount |
onetimeDiscountObject |
object |
One-time discount details |
subscriptionDiscountObject |
object |
Subscription discount details |
Example
const product = {
selected_variant: {
price: "49.99",
compare_at_price: "59.99"
}
};
const discountOptions = [
{ discountType: 'one-time', type: 'percentage', amount: 10 }
];
const result = Rebuy.util.calculateDiscount(product, true, discountOptions);
console.log(result);
// Output: {
// compareAtPrice: "59.99",
// discountedPrice: "44.99",
// savingAmount: 25, // ~25% off compare price
// type: "percentage",
// shouldShowDiscountedPrice: true,
// ...
// }
Objects
deepCopy
Creates a deep clone of an object or array using JSON serialization.
util.deepCopy(referenceValue);
Parameters
referenceValue · any · Required
- The value to clone (object, array, or primitive).
Returns
any - A deep copy of the input value.
Example
const original = {
product: { title: "T-Shirt", variants: [{ id: 1, price: "24.99" }] }
};
const copy = Rebuy.util.deepCopy(original);
copy.product.title = "Modified T-Shirt";
console.log(original.product.title);
// Output: 'T-Shirt' (unchanged)
console.log(copy.product.title);
// Output: 'Modified T-Shirt'
Limitations
Uses JSON.parse(JSON.stringify()) internally, so functions, undefined, Symbol, and circular references are not preserved.
extend
Merges multiple objects together, with optional deep merge support.
util.extend(deep, target, ...sources);
Parameters
deep · boolean
- If
true as first argument, performs deep merge. Otherwise, first argument is the target object.
target · object · Required
- The target object to merge into.
...sources · object
- Source objects to merge from (later objects override earlier ones).
Returns
object - The merged object.
Example
// Shallow merge
const defaults = { theme: 'light', limit: 5 };
const options = { limit: 10 };
const config = Rebuy.util.extend({}, defaults, options);
// Output: { theme: 'light', limit: 10 }
// Deep merge
const baseConfig = {
settings: { display: { columns: 4 }, api: { timeout: 5000 } }
};
const customConfig = {
settings: { display: { columns: 3 } }
};
const merged = Rebuy.util.extend(true, {}, baseConfig, customConfig);
// Output: { settings: { display: { columns: 3 }, api: { timeout: 5000 } } }
Use Cases
- Merging default configuration with custom options
- Creating new objects with combined properties
- Deep merging nested configuration objects
URLs
getLocation
Parses a URL and returns an object with its components.
Parameters
url · string
- The URL to parse. If omitted, uses
window.location.href.
Returns
object - URL components:
| Property |
Type |
Description |
hash |
string |
URL hash/fragment |
host |
string |
Hostname with port |
hostname |
string |
Hostname only |
href |
string |
Full URL |
pathname |
string |
URL path |
port |
string |
Port number |
protocol |
string |
Protocol (http:, https:) |
search |
string |
Query string |
Example
const location = Rebuy.util.getLocation("https://example.com:8080/products/shirt?color=blue#details");
console.log(location);
// Output: {
// hash: "#details",
// host: "example.com:8080",
// hostname: "example.com",
// href: "https://example.com:8080/products/shirt?color=blue#details",
// pathname: "/products/shirt",
// port: "8080",
// protocol: "https:",
// search: "?color=blue"
// }
generateCartShareUrl
Generates a shareable URL containing the current cart contents.
util.generateCartShareUrl();
Returns
string - URL with encoded cart data as a query parameter.
Example
// When cart contains items
const shareUrl = Rebuy.util.generateCartShareUrl();
console.log(shareUrl);
// Output: 'https://example.com/?rebuy_cart=eyJpdGVtcyI6W3siaWQiOjEyMzQ1Njc4OTAxMjMsInF1YW50aXR5IjoyfV19'
// Copy to clipboard for sharing
await Rebuy.util.copyToClipboard(shareUrl);
Use Cases
- "Share Cart" functionality
- Abandoned cart recovery links
- Customer service cart reconstruction
Requirements
Requires Smart Cart to be initialized with items in the cart.
Clipboard
copyToClipboard
Copies text to the user's clipboard.
await util.copyToClipboard(text);
Parameters
text · string · Required
- The text to copy to the clipboard.
Returns
Promise<void> - Resolves when copy is complete.
Throws
Error - If copy operation fails.
Example
// Copy a discount code
try {
await Rebuy.util.copyToClipboard('SAVE20');
console.log('Discount code copied!');
} catch (error) {
console.error('Failed to copy:', error);
}
// Copy cart share URL
const shareUrl = Rebuy.util.generateCartShareUrl();
await Rebuy.util.copyToClipboard(shareUrl);
Notes
- Uses the modern Clipboard API when available
- Falls back to
document.execCommand('copy') for older browsers
- May require user interaction (click event) in some browsers
Miscellaneous
debounce
Creates a debounced function that delays execution until after a specified wait time.
util.debounce(fn, wait, immediate);
Parameters
fn · function · Required
- The function to debounce.
wait · number · Required
- Milliseconds to wait before executing.
immediate · boolean · Default: false
- If
true, execute on the leading edge instead of trailing.
Returns
function - The debounced function.
Example
const searchProducts = Rebuy.util.debounce((query) => {
console.log('Searching for:', query);
// API call here
}, 300);
// Only executes once, 300ms after last call
searchProducts('shirt');
searchProducts('shirts');
searchProducts('shirts blue');
// Output after 300ms: 'Searching for: shirts blue'
filterArray
Filters an array of objects based on filter criteria.
util.filterArray(items, filters, possessive);
Parameters
items · array · Required
- Array of objects to filter.
filters · object · Required
- Filter criteria object.
possessive · boolean · Default: false
- If
true, items must match ALL filters.
Returns
array - Filtered array of items.
isRebuyItem
Checks if a cart item was added via a Rebuy widget.
Parameters
item · object · Required
- A Shopify cart item object.
Returns
boolean - true if the item was added via Rebuy.
Example
document.addEventListener('rebuy:cart.ready', (event) => {
const rebuyItems = event.detail.cart.items.filter(item =>
Rebuy.util.isRebuyItem(item)
);
console.log('Items added via Rebuy:', rebuyItems.length);
});
randomRange
Generates a random number within a specified range.
util.randomRange(min, max);
Parameters
min · number · Required
- Minimum value (inclusive).
max · number · Required
- Maximum value (inclusive).
Returns
number - Random number between min and max.
Example
const randomDiscount = Rebuy.util.randomRange(5, 20);
console.log(`You got ${randomDiscount}% off!`);
timestamp
Returns the current Unix timestamp in seconds.
Returns
number - Current Unix timestamp.
wait
Executes a callback after a specified delay.
Parameters
callback · function · Required
- Function to execute after the delay.
ms · number · Required
- Delay in milliseconds.
Example
Rebuy.util.wait(() => {
console.log('Executed after delay');
}, 2000);
---
title: Utility Methods
excerpt: Helper functions for formatting, products, objects, and common operations
deprecated: false
hidden: false
metadata:
title: ''
description: ''
robots: index
next:
description: ''
---
## Overview
Rebuy utilities provide helper functions for common operations including money formatting, product data manipulation, object handling, and more. All utilities are available on the global `Rebuy.util` namespace.
```javascript
const util = window.Rebuy.util;
```
---
## Quick Reference
| Category | Methods |
|----------|---------|
| **Formatting** | `formatMoney`, `formatNumber`, `numberWithCommas`, `amountToCents`, `handlize` |
| **Products** | `getStaticProducts`, `findLowestPricedVariant`, `findVariantBasedOnOptions`, `isBundleProduct`, `productImage` |
| **Discounts** | `calculateDiscount` |
| **Objects** | `deepCopy`, `extend` |
| **URLs** | `getLocation`, `generateCartShareUrl` |
| **Clipboard** | `copyToClipboard` |
| **Misc** | `debounce`, `filterArray`, `isRebuyItem`, `randomRange`, `timestamp`, `wait` |
---
## Formatting
### amountToCents
Converts a decimal amount to cents (integer).
```javascript
util.amountToCents(amount);
```
**Parameters**
`amount` · number | string · **Required**
: The amount to convert.
**Returns**
`number` - The amount in cents.
**Example**
```javascript
Rebuy.util.amountToCents(159.59);
// Output: 15959
Rebuy.util.amountToCents("24.99");
// Output: 2499
```
---
### formatMoney
Formats a cent value as a currency string wrapped in a `<span>` element.
```javascript
util.formatMoney(cents, format);
```
**Parameters**
`cents` · number · **Required**
: The amount in cents.
`format` · string · Default: shop's money format
: Custom format string using Shopify's money format syntax.
**Returns**
`string` - HTML span element with formatted money.
**Example**
```javascript
Rebuy.util.formatMoney(1299);
// Output: '<span class="money">$12.99</span>'
Rebuy.util.formatMoney(2499, "${{amount}}");
// Output: '<span class="money">$24.99</span>'
```
---
### formatNumber
Formats a number with thousands separators and decimal places.
```javascript
util.formatNumber(number, decimal_count, thousands_separator, decimal_separator);
```
**Parameters**
`number` · number | string · **Required**
: The number to format.
`decimal_count` · number · Default: `2`
: Number of decimal places.
`thousands_separator` · string · Default: `","`
: Character for thousands separation.
`decimal_separator` · string · Default: `"."`
: Character for decimal point.
**Returns**
`string` - The formatted number string.
**Example**
```javascript
Rebuy.util.formatNumber(1562, 2, ",", ".");
// Output: '1,562.00'
Rebuy.util.formatNumber(99999.5, 2, " ", ",");
// Output: '99 999,50'
```
---
### numberWithCommas
Formats a number with comma separators.
```javascript
util.numberWithCommas(num);
```
**Parameters**
`num` · number · **Required**
: The number to format.
**Returns**
`string` - The formatted number with commas.
**Example**
```javascript
Rebuy.util.numberWithCommas(1563);
// Output: '1,563'
Rebuy.util.numberWithCommas(1000000);
// Output: '1,000,000'
```
---
### handlize
Converts a string to a URL-safe handle (slug).
```javascript
util.handlize(str);
```
**Parameters**
`str` · string · **Required**
: The string to convert.
**Returns**
`string` - A lowercase, hyphenated handle.
**Example**
```javascript
Rebuy.util.handlize("Performance Half Zip Pullover");
// Output: 'performance-half-zip-pullover'
Rebuy.util.handlize("Men's T-Shirt (Large)");
// Output: 'mens-tshirt-large'
```
**Use Cases**
- Creating URL slugs from product titles
- Generating CSS class names from dynamic content
- Matching product handles to Shopify handles
---
## Products
### getStaticProducts
Fetches product data from the Rebuy `/products/static` endpoint. Returns full Shopify product data with support for contextual pricing and filtering options.
```javascript
await util.getStaticProducts(params);
```
**Parameters**
`params` · object
: Query parameters for the request.
| Property | Type | Description |
|----------|------|-------------|
| `ids` | string[] | Shopify product IDs to fetch |
| `handles` | string[] | Shopify product handles to fetch |
| `shopify_product_ids` | string[] | Product IDs to filter from results |
| `shopify_collection_id` | string | Collection ID to filter products |
| `country_code` | string | ISO country code for contextual pricing (e.g., 'US') |
| `metafields` | string | Set to `'yes'` to include product metafields |
| `limit` | string | Number of results to return (default: 5) |
| `bust_cache` | string | Set to `'yes'` to force a fresh response |
**Returns**
`Promise<object>` - Response containing `data` array of product objects.
**Example**
```javascript
// Fetch specific products by IDs
const response = await Rebuy.util.getStaticProducts({
ids: ['8234567890123', '8234567890456']
});
console.log(response.data);
// Output: [{ id: 8234567890123, title: 'Product 1', ... }, ...]
// Fetch products with contextual pricing for Canada
const caProducts = await Rebuy.util.getStaticProducts({
ids: ['8234567890123'],
country_code: 'CA',
metafields: 'yes'
});
// Fetch products from a collection
const collectionProducts = await Rebuy.util.getStaticProducts({
shopify_collection_id: '123456789012',
limit: '10'
});
```
**Use Cases**
- Loading product data for custom widgets
- Fetching product details for comparison features
- Getting contextual pricing for international customers
!!! note "API Documentation"
See the [Static Products API](static.md) for full endpoint documentation.
---
### findLowestPricedVariant
Finds the variant with the lowest price from a product's variants array.
```javascript
util.findLowestPricedVariant(product);
```
**Parameters**
`product` · object · **Required**
: A Rebuy product object containing a `variants` array.
**Returns**
`object` - The variant object with the lowest price, or empty object if no variants.
**Example**
```javascript
const product = {
title: "Classic T-Shirt",
variants: [
{ id: 1, title: "Small", price: "24.99" },
{ id: 2, title: "Medium", price: "24.99" },
{ id: 3, title: "Large", price: "29.99" }
]
};
const cheapestVariant = Rebuy.util.findLowestPricedVariant(product);
console.log(cheapestVariant);
// Output: { id: 1, title: "Small", price: "24.99" }
```
**Use Cases**
- Displaying "Starting at $X" pricing
- Auto-selecting the most affordable variant
- Price comparison features
---
### findVariantBasedOnOptions
Finds a variant that matches the currently selected product options.
```javascript
util.findVariantBasedOnOptions(product);
```
**Parameters**
`product` · object · **Required**
: A product object with `variants` array and `option1`, `option2`, `option3` properties set to the selected option values.
**Returns**
`object | null` - The matching variant object, or `null` if no match found.
**Example**
```javascript
const product = {
option1: "Blue",
option2: "Medium",
option3: null,
variants: [
{ id: 1, option1: "Blue", option2: "Small", option3: null, price: "24.99" },
{ id: 2, option1: "Blue", option2: "Medium", option3: null, price: "24.99" },
{ id: 3, option1: "Red", option2: "Medium", option3: null, price: "24.99" }
]
};
const selectedVariant = Rebuy.util.findVariantBasedOnOptions(product);
console.log(selectedVariant);
// Output: { id: 2, option1: "Blue", option2: "Medium", option3: null, price: "24.99" }
```
**Use Cases**
- Custom variant selectors
- Syncing variant selection across multiple option dropdowns
- Programmatic variant selection
---
### isBundleProduct
Checks whether a cart item is a Shopify bundle product.
```javascript
util.isBundleProduct(item);
```
**Parameters**
`item` · object · **Required**
: A Shopify cart item object.
**Returns**
`boolean` - `true` if the item is a bundle product, `false` otherwise.
**Example**
```javascript
document.addEventListener('rebuy:cart.ready', (event) => {
const cart = event.detail.cart;
cart.items.forEach(item => {
if (Rebuy.util.isBundleProduct(item)) {
console.log(`${item.title} is a bundle product`);
}
});
});
```
**Notes**
- Detects products created via Shopify's Bundles app
- Products using Cart Transform API with only a default variant are not considered bundles
---
### productImage
Resizes a product image URL to a specific size.
```javascript
util.productImage(product, size);
```
**Parameters**
`product` · object · **Required**
: A product or variant object with an image property.
`size` · string · Default: `"medium"`
: The desired image size (e.g., `"small"`, `"medium"`, `"large"`, or pixel dimensions like `"300x300"`).
**Returns**
`string` - The resized image URL.
---
## Discounts
### calculateDiscount
Calculates discounted pricing for a product based on discount options.
```javascript
util.calculateDiscount(product, isCompareAtPrice, discountOptions);
```
**Parameters**
`product` · object · **Required**
: A product object with `selected_variant` containing price information.
`isCompareAtPrice` · boolean · **Required**
: Whether to use the compare-at price as the baseline.
`discountOptions` · array
: Array of discount option objects with `discountType` (`'one-time'` or `'subscription'`), `type` (`'percentage'`, `'fixed_amount'`, or `'price'`), and `amount`.
**Returns**
`object` - Calculated discount information:
| Property | Type | Description |
|----------|------|-------------|
| `compareAtPrice` | number | Original/compare price |
| `discountedPrice` | number | Final discounted price |
| `savingAmount` | number | Amount saved (percentage or fixed) |
| `type` | string | Discount type used |
| `shouldShowDiscountedPrice` | boolean | Whether to display the discount |
| `onetimeDiscountObject` | object | One-time discount details |
| `subscriptionDiscountObject` | object | Subscription discount details |
**Example**
```javascript
const product = {
selected_variant: {
price: "49.99",
compare_at_price: "59.99"
}
};
const discountOptions = [
{ discountType: 'one-time', type: 'percentage', amount: 10 }
];
const result = Rebuy.util.calculateDiscount(product, true, discountOptions);
console.log(result);
// Output: {
// compareAtPrice: "59.99",
// discountedPrice: "44.99",
// savingAmount: 25, // ~25% off compare price
// type: "percentage",
// shouldShowDiscountedPrice: true,
// ...
// }
```
---
## Objects
### deepCopy
Creates a deep clone of an object or array using JSON serialization.
```javascript
util.deepCopy(referenceValue);
```
**Parameters**
`referenceValue` · any · **Required**
: The value to clone (object, array, or primitive).
**Returns**
`any` - A deep copy of the input value.
**Example**
```javascript
const original = {
product: { title: "T-Shirt", variants: [{ id: 1, price: "24.99" }] }
};
const copy = Rebuy.util.deepCopy(original);
copy.product.title = "Modified T-Shirt";
console.log(original.product.title);
// Output: 'T-Shirt' (unchanged)
console.log(copy.product.title);
// Output: 'Modified T-Shirt'
```
!!! warning "Limitations"
Uses `JSON.parse(JSON.stringify())` internally, so functions, `undefined`, `Symbol`, and circular references are not preserved.
---
### extend
Merges multiple objects together, with optional deep merge support.
```javascript
util.extend(deep, target, ...sources);
```
**Parameters**
`deep` · boolean
: If `true` as first argument, performs deep merge. Otherwise, first argument is the target object.
`target` · object · **Required**
: The target object to merge into.
`...sources` · object
: Source objects to merge from (later objects override earlier ones).
**Returns**
`object` - The merged object.
**Example**
```javascript
// Shallow merge
const defaults = { theme: 'light', limit: 5 };
const options = { limit: 10 };
const config = Rebuy.util.extend({}, defaults, options);
// Output: { theme: 'light', limit: 10 }
// Deep merge
const baseConfig = {
settings: { display: { columns: 4 }, api: { timeout: 5000 } }
};
const customConfig = {
settings: { display: { columns: 3 } }
};
const merged = Rebuy.util.extend(true, {}, baseConfig, customConfig);
// Output: { settings: { display: { columns: 3 }, api: { timeout: 5000 } } }
```
**Use Cases**
- Merging default configuration with custom options
- Creating new objects with combined properties
- Deep merging nested configuration objects
---
## URLs
### getLocation
Parses a URL and returns an object with its components.
```javascript
util.getLocation(url);
```
**Parameters**
`url` · string
: The URL to parse. If omitted, uses `window.location.href`.
**Returns**
`object` - URL components:
| Property | Type | Description |
|----------|------|-------------|
| `hash` | string | URL hash/fragment |
| `host` | string | Hostname with port |
| `hostname` | string | Hostname only |
| `href` | string | Full URL |
| `pathname` | string | URL path |
| `port` | string | Port number |
| `protocol` | string | Protocol (http:, https:) |
| `search` | string | Query string |
**Example**
```javascript
const location = Rebuy.util.getLocation("https://example.com:8080/products/shirt?color=blue#details");
console.log(location);
// Output: {
// hash: "#details",
// host: "example.com:8080",
// hostname: "example.com",
// href: "https://example.com:8080/products/shirt?color=blue#details",
// pathname: "/products/shirt",
// port: "8080",
// protocol: "https:",
// search: "?color=blue"
// }
```
---
### generateCartShareUrl
Generates a shareable URL containing the current cart contents.
```javascript
util.generateCartShareUrl();
```
**Returns**
`string` - URL with encoded cart data as a query parameter.
**Example**
```javascript
// When cart contains items
const shareUrl = Rebuy.util.generateCartShareUrl();
console.log(shareUrl);
// Output: 'https://example.com/?rebuy_cart=eyJpdGVtcyI6W3siaWQiOjEyMzQ1Njc4OTAxMjMsInF1YW50aXR5IjoyfV19'
// Copy to clipboard for sharing
await Rebuy.util.copyToClipboard(shareUrl);
```
**Use Cases**
- "Share Cart" functionality
- Abandoned cart recovery links
- Customer service cart reconstruction
!!! note "Requirements"
Requires Smart Cart to be initialized with items in the cart.
---
## Clipboard
### copyToClipboard
Copies text to the user's clipboard.
```javascript
await util.copyToClipboard(text);
```
**Parameters**
`text` · string · **Required**
: The text to copy to the clipboard.
**Returns**
`Promise<void>` - Resolves when copy is complete.
**Throws**
`Error` - If copy operation fails.
**Example**
```javascript
// Copy a discount code
try {
await Rebuy.util.copyToClipboard('SAVE20');
console.log('Discount code copied!');
} catch (error) {
console.error('Failed to copy:', error);
}
// Copy cart share URL
const shareUrl = Rebuy.util.generateCartShareUrl();
await Rebuy.util.copyToClipboard(shareUrl);
```
**Notes**
- Uses the modern Clipboard API when available
- Falls back to `document.execCommand('copy')` for older browsers
- May require user interaction (click event) in some browsers
---
## Miscellaneous
### debounce
Creates a debounced function that delays execution until after a specified wait time.
```javascript
util.debounce(fn, wait, immediate);
```
**Parameters**
`fn` · function · **Required**
: The function to debounce.
`wait` · number · **Required**
: Milliseconds to wait before executing.
`immediate` · boolean · Default: `false`
: If `true`, execute on the leading edge instead of trailing.
**Returns**
`function` - The debounced function.
**Example**
```javascript
const searchProducts = Rebuy.util.debounce((query) => {
console.log('Searching for:', query);
// API call here
}, 300);
// Only executes once, 300ms after last call
searchProducts('shirt');
searchProducts('shirts');
searchProducts('shirts blue');
// Output after 300ms: 'Searching for: shirts blue'
```
---
### filterArray
Filters an array of objects based on filter criteria.
```javascript
util.filterArray(items, filters, possessive);
```
**Parameters**
`items` · array · **Required**
: Array of objects to filter.
`filters` · object · **Required**
: Filter criteria object.
`possessive` · boolean · Default: `false`
: If `true`, items must match ALL filters.
**Returns**
`array` - Filtered array of items.
---
### isRebuyItem
Checks if a cart item was added via a Rebuy widget.
```javascript
util.isRebuyItem(item);
```
**Parameters**
`item` · object · **Required**
: A Shopify cart item object.
**Returns**
`boolean` - `true` if the item was added via Rebuy.
**Example**
```javascript
document.addEventListener('rebuy:cart.ready', (event) => {
const rebuyItems = event.detail.cart.items.filter(item =>
Rebuy.util.isRebuyItem(item)
);
console.log('Items added via Rebuy:', rebuyItems.length);
});
```
---
### randomRange
Generates a random number within a specified range.
```javascript
util.randomRange(min, max);
```
**Parameters**
`min` · number · **Required**
: Minimum value (inclusive).
`max` · number · **Required**
: Maximum value (inclusive).
**Returns**
`number` - Random number between min and max.
**Example**
```javascript
const randomDiscount = Rebuy.util.randomRange(5, 20);
console.log(`You got ${randomDiscount}% off!`);
```
---
### timestamp
Returns the current Unix timestamp in seconds.
```javascript
util.timestamp();
```
**Returns**
`number` - Current Unix timestamp.
---
### wait
Executes a callback after a specified delay.
```javascript
util.wait(callback, ms);
```
**Parameters**
`callback` · function · **Required**
: Function to execute after the delay.
`ms` · number · **Required**
: Delay in milliseconds.
**Example**
```javascript
Rebuy.util.wait(() => {
console.log('Executed after delay');
}, 2000);
```
---
## Related
- [Cart Methods](cart-methods.md)
- [Widget Methods](widget-methods.md)
- [Static Products API](static.md)
<!-- Source: onsite-js/src/onsite/js/utilities/ -->