All files / app/address isEqualAddress.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50  24x         24x 102x 6x     96x             42x 38x     4x 1x     3x         192x                   192x     35x          
import { Address, AddressRequestBody, BillingAddress, CustomerAddress } from '@bigcommerce/checkout-sdk';
import { isEqual, omit } from 'lodash';
 
type ComparableAddress = CustomerAddress | Address | BillingAddress | AddressRequestBody;
type ComparableAddressFields = keyof CustomerAddress | keyof Address | keyof BillingAddress;
 
export default function isEqualAddress(address1?: ComparableAddress, address2?: ComparableAddress): boolean {
    if (!address1 || !address2) {
        return false;
    }
 
    return isEqual(
        normalizeAddress(address1),
        normalizeAddress(address2)
    ) && isSameState(address1, address2);
}
 
function isSameState(address1: ComparableAddress, address2: ComparableAddress): boolean {
    if (address1.stateOrProvince && address1.stateOrProvince === address2.stateOrProvince) {
        return true;
    }
 
    if (address1.stateOrProvinceCode && address1.stateOrProvinceCode === address2.stateOrProvinceCode) {
        return true;
    }
 
    return address1.stateOrProvince === address2.stateOrProvince &&
        address1.stateOrProvinceCode === address2.stateOrProvinceCode;
}
 
function normalizeAddress(address: ComparableAddress) {
    const ignoredFields: ComparableAddressFields[] = [
        'id',
        'shouldSaveAddress',
        'stateOrProvince',
        'stateOrProvinceCode',
        'type',
        'email',
        'country',
    ];
 
    return omit(
        {
            ...address,
            customFields: (address.customFields || []).filter(({ fieldValue }) => !!fieldValue),
        },
        ignoredFields
    );
}