@fileverse-dev/formulajs 4.4.20-mod-1 → 4.4.20-mod-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/esm/index.mjs CHANGED
@@ -1439,115 +1439,402 @@ function VLOOKUP(lookup_value, table_array, col_index_num, range_lookup) {
1439
1439
  return result
1440
1440
  }
1441
1441
 
1442
- function XLOOKUP(lookup_value, lookup_array, return_array, if_not_found, match_mode, search_mode) {
1443
- // Handle case where error object might not be defined
1442
+ function XLOOKUP(search_key, lookup_range, result_range, missing_value, isCol,match_mode, search_mode) {
1443
+ // Error constants
1444
1444
  const ERROR_NA = '#N/A';
1445
1445
  const ERROR_REF = '#REF!';
1446
+ const ERROR_VALUE = '#VALUE!';
1447
+ const ERROR_NUM = '#NUM!';
1446
1448
 
1447
- console.log('XLOOKUP parameters:', { lookup_value, lookup_array, return_array, if_not_found, match_mode, search_mode });
1449
+ console.log('XLOOKUP parameters:', { search_key, lookup_range, result_range, missing_value, match_mode, search_mode, isCol });
1448
1450
 
1449
- console.log('XLOOKUP called with:', { lookup_value, lookup_array, return_array, if_not_found, match_mode, search_mode });
1451
+ // Validate required parameters
1452
+ if (search_key === undefined || search_key === null) {
1453
+ console.log('Error: search_key is required');
1454
+ return ERROR_VALUE
1455
+ }
1456
+
1457
+ if (!lookup_range || !result_range) {
1458
+ console.log('Error: lookup_range and result_range are required');
1459
+ return ERROR_REF
1460
+ }
1461
+
1462
+ // Validate and normalize lookup_range (must be singular row or column)
1463
+ let lookup_array = normalizeLookupRange(lookup_range);
1464
+ if (!lookup_array) {
1465
+ console.log('Error: lookup_range must be a singular row or column');
1466
+ return ERROR_REF
1467
+ }
1468
+
1469
+ // Validate and normalize result_range
1470
+ let result_array = normalizeResultRange(result_range);
1471
+ if (!result_array) {
1472
+ console.log('Error: Invalid result_range');
1473
+ return ERROR_REF
1474
+ }
1475
+
1476
+ // Validate that lookup and result ranges have compatible dimensions
1477
+ // Exception: if result_range is a single row, it can be returned regardless of lookup_range length
1478
+ result_array.length === 1;
1479
+
1480
+ // if (!isSingleResultRow && lookup_array.length !== result_array.length) {
1481
+ // console.log('Error: lookup_range and result_range must have the same number of rows/entries (unless result_range is a single row)')
1482
+ // return ERROR_REF
1483
+ // }
1484
+
1485
+ // Set default parameter values
1486
+ missing_value = missing_value !== undefined ? missing_value : ERROR_NA;
1487
+ match_mode = match_mode !== undefined ? match_mode : 0;
1488
+ search_mode = search_mode !== undefined ? search_mode : 1;
1489
+ isCol = isCol !== undefined ? isCol : false;
1490
+
1491
+ // Validate match_mode
1492
+ if (![0, 1, -1, 2].includes(match_mode)) {
1493
+ console.log('Error: match_mode must be 0, 1, -1, or 2');
1494
+ return ERROR_NUM
1495
+ }
1496
+
1497
+ // Validate search_mode
1498
+ if (![1, -1, 2, -2].includes(search_mode)) {
1499
+ console.log('Error: search_mode must be 1, -1, 2, or -2');
1500
+ return ERROR_NUM
1501
+ }
1502
+
1503
+ // Validate binary search requirements
1504
+ if (Math.abs(search_mode) === 2 && match_mode === 2) {
1505
+ console.log('Error: Binary search (search_mode ±2) cannot be used with wildcard matching (match_mode 2)');
1506
+ return ERROR_VALUE
1507
+ }
1508
+
1509
+ console.log('Normalized arrays:', { lookup_array, result_array });
1510
+
1511
+ return performLookup(search_key, lookup_array, result_array, missing_value, match_mode, search_mode, isCol)
1512
+ }
1513
+
1514
+ function normalizeLookupRange(lookup_range) {
1515
+ if (!Array.isArray(lookup_range)) {
1516
+ return null
1517
+ }
1518
+
1519
+ // If it's a 1D array, it's already a column
1520
+ if (!Array.isArray(lookup_range[0])) {
1521
+ return lookup_range
1522
+ }
1523
+
1524
+ // If it's a 2D array, check if it's a single row or single column
1525
+ const rows = lookup_range.length;
1526
+ const cols = lookup_range[0].length;
1450
1527
 
1451
- // Handle VLOOKUP-style call: XLOOKUP("a", F7:G9, 2, "false")
1452
- if (typeof return_array === 'number' && Array.isArray(lookup_array) && Array.isArray(lookup_array[0])) {
1453
- console.log('Detected VLOOKUP-style call');
1454
- const table_array = lookup_array;
1455
- const col_index_num = return_array;
1456
- const range_lookup = !(if_not_found === "false" || if_not_found === false || if_not_found === 0);
1528
+ if (rows === 1) {
1529
+ // Single row - extract as array
1530
+ return lookup_range[0]
1531
+ } else if (cols === 1) {
1532
+ // Single column - extract first element of each row
1533
+ return lookup_range.map(row => row[0])
1534
+ } else {
1535
+ // Multiple rows and columns - not allowed
1536
+ return null
1537
+ }
1538
+ }
1539
+
1540
+ function normalizeResultRange(result_range) {
1541
+ if (!Array.isArray(result_range)) {
1542
+ return null
1543
+ }
1544
+
1545
+ // If it's a 1D array, convert to 2D single column for consistency
1546
+ if (!Array.isArray(result_range[0])) {
1547
+ return result_range.map(value => [value])
1548
+ }
1549
+
1550
+ // If it's already 2D, return as is
1551
+ return result_range
1552
+ }
1553
+
1554
+ function performLookup(search_key, lookup_array, result_array, missing_value, match_mode, search_mode, isCol) {
1555
+
1556
+ console.log('performLookup called with:', { search_key, lookup_array, result_array, missing_value, match_mode, search_mode, isCol });
1557
+
1558
+ let foundIndex = -1;
1559
+
1560
+ // Handle different match modes
1561
+ switch (match_mode) {
1562
+ case 0: // Exact match
1563
+ foundIndex = findExactMatch(search_key, lookup_array, search_mode);
1564
+ break
1565
+ case 1: // Exact match or next larger
1566
+ foundIndex = findExactOrNextLarger(search_key, lookup_array, search_mode);
1567
+ break
1568
+ case -1: // Exact match or next smaller
1569
+ foundIndex = findExactOrNextSmaller(search_key, lookup_array, search_mode);
1570
+ break
1571
+ case 2: // Wildcard match
1572
+ foundIndex = findWildcardMatch(search_key, lookup_array, search_mode);
1573
+ break
1574
+ }
1575
+
1576
+ if (foundIndex === -1) {
1577
+ // No match found
1578
+ if (result_array[0].length > 1) {
1579
+ // Multiple columns
1580
+ const errorArray = new Array(result_array[0].length).fill(missing_value);
1581
+ if (isCol) {
1582
+ // Return as column format: [["error"], ["error"], ...]
1583
+ return errorArray.map(val => [val])
1584
+ } else {
1585
+ // Return as row format: ["error", "error", ...]
1586
+ return errorArray
1587
+ }
1588
+ } else {
1589
+ // Single column - return single missing value (isCol doesn't affect single values)
1590
+ return missing_value
1591
+ }
1592
+ }
1593
+
1594
+ // Return the result
1595
+ if (result_array[0].length === 1) {
1596
+ // Single column result - isCol doesn't affect single values
1597
+ return result_array[foundIndex][0]
1598
+ } else {
1599
+ // Multiple column result
1600
+ if (isCol) {
1601
+ // Return as column format: [["val1"], ["val2"], ["val3"]]
1602
+ return result_array[foundIndex].map(val => [val])
1603
+ } else {
1604
+ // Return as row format: ["val1", "val2", "val3"]
1605
+ return result_array[foundIndex]
1606
+ }
1607
+ }
1608
+ }
1609
+
1610
+ function findExactMatch(search_key, lookup_array, search_mode) {
1611
+ const processedSearchKey = typeof search_key === 'string' ? search_key.toLowerCase().trim() : search_key;
1612
+
1613
+ if (Math.abs(search_mode) === 2) {
1614
+ // Binary search
1615
+ return binarySearchExact(processedSearchKey, lookup_array, search_mode > 0)
1616
+ } else {
1617
+ // Linear search
1618
+ const indices = getSearchIndices(lookup_array.length, search_mode);
1457
1619
 
1458
- // Validate column index
1459
- if (col_index_num < 1 || col_index_num > table_array[0].length) {
1460
- return ERROR_REF
1620
+ for (const i of indices) {
1621
+ const value = lookup_array[i];
1622
+ const processedValue = typeof value === 'string' ? value.toLowerCase().trim() : value;
1623
+
1624
+ if (processedValue === processedSearchKey) {
1625
+ console.log(`Exact match found at index ${i}:`, value);
1626
+ return i
1627
+ }
1461
1628
  }
1629
+ }
1630
+
1631
+ return -1
1632
+ }
1633
+
1634
+ function findExactOrNextLarger(search_key, lookup_array, search_mode) {
1635
+ const isNumber = typeof search_key === 'number';
1636
+ const processedSearchKey = typeof search_key === 'string' ? search_key.toLowerCase().trim() : search_key;
1637
+
1638
+ if (Math.abs(search_mode) === 2) {
1639
+ // Binary search for exact or next larger
1640
+ return binarySearchNextLarger(processedSearchKey, lookup_array, search_mode > 0)
1641
+ }
1642
+
1643
+ const indices = getSearchIndices(lookup_array.length, search_mode);
1644
+ let bestIndex = -1;
1645
+
1646
+ for (const i of indices) {
1647
+ const value = lookup_array[i];
1648
+ const processedValue = typeof value === 'string' ? value.toLowerCase().trim() : value;
1462
1649
 
1463
- // Extract lookup and return columns
1464
- const lookup_col = table_array.map(row => row[0]);
1465
- const return_col = table_array.map(row => row[col_index_num - 1]);
1650
+ // Exact match
1651
+ if (processedValue === processedSearchKey) {
1652
+ return i
1653
+ }
1466
1654
 
1467
- return performLookup(lookup_value, lookup_col, return_col, ERROR_NA, range_lookup ? -1 : 0)
1655
+ // Next larger value
1656
+ if (isNumber && typeof value === 'number' && value > search_key) {
1657
+ if (bestIndex === -1 || value < lookup_array[bestIndex]) {
1658
+ bestIndex = i;
1659
+ }
1660
+ } else if (!isNumber && typeof value === 'string' && processedValue > processedSearchKey) {
1661
+ if (bestIndex === -1 || processedValue < (typeof lookup_array[bestIndex] === 'string' ? lookup_array[bestIndex].toLowerCase().trim() : lookup_array[bestIndex])) {
1662
+ bestIndex = i;
1663
+ }
1664
+ }
1468
1665
  }
1469
1666
 
1470
- // Standard XLOOKUP call: XLOOKUP("a", F7:F9, G7:G9, "hahaha")
1471
- console.log('Detected standard XLOOKUP call');
1667
+ return bestIndex
1668
+ }
1669
+
1670
+ function findExactOrNextSmaller(search_key, lookup_array, search_mode) {
1671
+ const isNumber = typeof search_key === 'number';
1672
+ const processedSearchKey = typeof search_key === 'string' ? search_key.toLowerCase().trim() : search_key;
1472
1673
 
1473
- if (!lookup_array || !return_array) {
1474
- console.log('Missing lookup_array or return_array');
1475
- return ERROR_NA
1674
+ if (Math.abs(search_mode) === 2) {
1675
+ // Binary search for exact or next smaller
1676
+ return binarySearchNextSmaller(processedSearchKey, lookup_array, search_mode > 0)
1476
1677
  }
1477
1678
 
1478
- // Handle case where arrays might be 2D (from Excel ranges)
1479
- let lookup_col = lookup_array;
1480
- let return_col = return_array;
1679
+ const indices = getSearchIndices(lookup_array.length, search_mode);
1680
+ let bestIndex = -1;
1481
1681
 
1482
- // If lookup_array is 2D, extract first column
1483
- if (Array.isArray(lookup_array) && Array.isArray(lookup_array[0])) {
1484
- lookup_col = lookup_array.map(row => row[0]);
1485
- console.log('Extracted lookup column from 2D array:', lookup_col);
1682
+ for (const i of indices) {
1683
+ const value = lookup_array[i];
1684
+ const processedValue = typeof value === 'string' ? value.toLowerCase().trim() : value;
1685
+
1686
+ // Exact match
1687
+ if (processedValue === processedSearchKey) {
1688
+ return i
1689
+ }
1690
+
1691
+ // Next smaller value
1692
+ if (isNumber && typeof value === 'number' && value < search_key) {
1693
+ if (bestIndex === -1 || value > lookup_array[bestIndex]) {
1694
+ bestIndex = i;
1695
+ }
1696
+ } else if (!isNumber && typeof value === 'string' && processedValue < processedSearchKey) {
1697
+ if (bestIndex === -1 || processedValue > (typeof lookup_array[bestIndex] === 'string' ? lookup_array[bestIndex].toLowerCase().trim() : lookup_array[bestIndex])) {
1698
+ bestIndex = i;
1699
+ }
1700
+ }
1486
1701
  }
1487
1702
 
1488
- // If return_array is 2D, extract first column
1489
- if (Array.isArray(return_array) && Array.isArray(return_array[0])) {
1490
- return_col = return_array.map(row => row[0]);
1491
- console.log('Extracted return column from 2D array:', return_col);
1703
+ return bestIndex
1704
+ }
1705
+
1706
+ function findWildcardMatch(search_key, lookup_array, search_mode) {
1707
+ if (typeof search_key !== 'string') {
1708
+ return -1 // Wildcard only works with strings
1492
1709
  }
1493
1710
 
1494
- if (lookup_col.length !== return_col.length) {
1495
- console.log('Array length mismatch:', lookup_col.length, 'vs', return_col.length);
1496
- return ERROR_NA
1497
- }
1711
+ // Convert wildcard pattern to regex
1712
+ const pattern = search_key
1713
+ .toLowerCase()
1714
+ .replace(/\*/g, '.*') // * matches any sequence of characters
1715
+ .replace(/\?/g, '.') // ? matches any single character
1716
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape other regex chars
1717
+ .replace(/\\\.\*/g, '.*') // Restore our wildcards
1718
+ .replace(/\\\./g, '.');
1719
+
1720
+ const regex = new RegExp(`^${pattern}$`, 'i');
1498
1721
 
1499
- // Default parameters
1500
- if_not_found = if_not_found !== undefined ? if_not_found : ERROR_NA;
1501
- match_mode = match_mode || 0; // 0 = exact match, -1 = exact or next smallest
1502
- search_mode = search_mode || 1; // 1 = first to last, -1 = last to first
1722
+ const indices = getSearchIndices(lookup_array.length, search_mode);
1723
+
1724
+ for (const i of indices) {
1725
+ const value = lookup_array[i];
1726
+ if (typeof value === 'string' && regex.test(value)) {
1727
+ console.log(`Wildcard match found at index ${i}:`, value);
1728
+ return i
1729
+ }
1730
+ }
1503
1731
 
1504
- return performLookup(lookup_value, lookup_col, return_col, if_not_found, match_mode, search_mode)
1732
+ return -1
1505
1733
  }
1506
1734
 
1735
+ function getSearchIndices(length, search_mode) {
1736
+ if (search_mode === -1) {
1737
+ // Last to first
1738
+ return Array.from({ length }, (_, i) => length - 1 - i)
1739
+ } else {
1740
+ // First to last (default)
1741
+ return Array.from({ length }, (_, i) => i)
1742
+ }
1743
+ }
1507
1744
 
1508
- function performLookup(lookup_value, lookup_array, return_array, if_not_found, match_mode, search_mode) {
1509
- const isNumberLookup = typeof lookup_value === 'number';
1510
- const lookupValue = typeof lookup_value === 'string' ? lookup_value.toLowerCase().trim() : lookup_value;
1511
- let bestMatchIndex = -1;
1745
+ function binarySearchExact(search_key, lookup_array, ascending) {
1746
+ let left = 0;
1747
+ let right = lookup_array.length - 1;
1512
1748
 
1513
- // Debug: Log what we're looking for and what we have
1514
- console.log('XLOOKUP Debug:', {
1515
- looking_for: lookup_value,
1516
- processed_lookup: lookupValue,
1517
- lookup_array: lookup_array,
1518
- return_array: return_array,
1519
- match_mode: match_mode
1520
- });
1749
+ while (left <= right) {
1750
+ const mid = Math.floor((left + right) / 2);
1751
+ const midValue = lookup_array[mid];
1752
+ const processedMidValue = typeof midValue === 'string' ? midValue.toLowerCase().trim() : midValue;
1753
+
1754
+ if (processedMidValue === search_key) {
1755
+ return mid
1756
+ }
1757
+
1758
+ const comparison = ascending ?
1759
+ (processedMidValue < search_key) :
1760
+ (processedMidValue > search_key);
1761
+
1762
+ if (comparison) {
1763
+ left = mid + 1;
1764
+ } else {
1765
+ right = mid - 1;
1766
+ }
1767
+ }
1521
1768
 
1522
- // Determine search direction
1523
- const startIndex = search_mode === -1 ? lookup_array.length - 1 : 0;
1524
- const endIndex = search_mode === -1 ? -1 : lookup_array.length;
1525
- const step = search_mode === -1 ? -1 : 1;
1769
+ return -1
1770
+ }
1771
+
1772
+ function binarySearchNextLarger(search_key, lookup_array, ascending) {
1773
+ let left = 0;
1774
+ let right = lookup_array.length - 1;
1775
+ let result = -1;
1526
1776
 
1527
- for (let i = startIndex; i !== endIndex; i += step) {
1528
- const rawValue = lookup_array[i];
1529
- const arrayValue = typeof rawValue === 'string' ? rawValue.toLowerCase().trim() : rawValue;
1777
+ while (left <= right) {
1778
+ const mid = Math.floor((left + right) / 2);
1779
+ const midValue = lookup_array[mid];
1780
+ const processedMidValue = typeof midValue === 'string' ? midValue.toLowerCase().trim() : midValue;
1530
1781
 
1531
- console.log(`Comparing: "${lookupValue}" === "${arrayValue}" (types: ${typeof lookupValue} vs ${typeof arrayValue})`);
1782
+ if (processedMidValue === search_key) {
1783
+ return mid // Exact match
1784
+ }
1532
1785
 
1533
- // Exact match
1534
- if (arrayValue === lookupValue) {
1535
- console.log(`Found match at index ${i}: ${return_array[i]}`);
1536
- return return_array[i]
1786
+ if (ascending) {
1787
+ if (processedMidValue > search_key) {
1788
+ result = mid;
1789
+ right = mid - 1;
1790
+ } else {
1791
+ left = mid + 1;
1792
+ }
1793
+ } else {
1794
+ if (processedMidValue < search_key) {
1795
+ result = mid;
1796
+ left = mid + 1;
1797
+ } else {
1798
+ right = mid - 1;
1799
+ }
1537
1800
  }
1801
+ }
1802
+
1803
+ return result
1804
+ }
1805
+
1806
+ function binarySearchNextSmaller(search_key, lookup_array, ascending) {
1807
+ let left = 0;
1808
+ let right = lookup_array.length - 1;
1809
+ let result = -1;
1810
+
1811
+ while (left <= right) {
1812
+ const mid = Math.floor((left + right) / 2);
1813
+ const midValue = lookup_array[mid];
1814
+ const processedMidValue = typeof midValue === 'string' ? midValue.toLowerCase().trim() : midValue;
1538
1815
 
1539
- // Approximate match (match_mode = -1, similar to VLOOKUP range_lookup = true)
1540
- if (match_mode === -1) {
1541
- if ((isNumberLookup && typeof arrayValue === 'number' && arrayValue <= lookup_value) ||
1542
- (!isNumberLookup && typeof arrayValue === 'string' && arrayValue.localeCompare(lookupValue) <= 0)) {
1543
- bestMatchIndex = i;
1544
- console.log(`Approximate match candidate at index ${i}: ${arrayValue}`);
1816
+ if (processedMidValue === search_key) {
1817
+ return mid // Exact match
1818
+ }
1819
+
1820
+ if (ascending) {
1821
+ if (processedMidValue < search_key) {
1822
+ result = mid;
1823
+ left = mid + 1;
1824
+ } else {
1825
+ right = mid - 1;
1826
+ }
1827
+ } else {
1828
+ if (processedMidValue > search_key) {
1829
+ result = mid;
1830
+ right = mid - 1;
1831
+ } else {
1832
+ left = mid + 1;
1545
1833
  }
1546
1834
  }
1547
1835
  }
1548
1836
 
1549
- console.log(`No exact match found. Returning: ${bestMatchIndex !== -1 ? return_array[bestMatchIndex] : if_not_found}`);
1550
- return bestMatchIndex !== -1 ? return_array[bestMatchIndex] : if_not_found
1837
+ return result
1551
1838
  }
1552
1839
 
1553
1840
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fileverse-dev/formulajs",
3
- "version": "4.4.20-mod-1",
3
+ "version": "4.4.20-mod-2",
4
4
  "description": "JavaScript implementation of most Microsoft Excel formula functions",
5
5
  "author": "Formulajs",
6
6
  "publishConfig": {
@@ -4522,7 +4522,7 @@ export function WORKDAY_INTL(start_date: any, days: any, weekend: any, holidays:
4522
4522
  * @returns
4523
4523
  */
4524
4524
  export function XIRR(values: any, dates: any, guess: any): any;
4525
- export function XLOOKUP(lookup_value: any, lookup_array: any, return_array: any, if_not_found: any, match_mode: any, search_mode: any): any;
4525
+ export function XLOOKUP(search_key: any, lookup_range: any, result_range: any, missing_value: any, isCol: any, match_mode: any, search_mode: any): any;
4526
4526
  /**
4527
4527
  * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
4528
4528
  *
@@ -4522,7 +4522,7 @@ export function WORKDAY_INTL(start_date: any, days: any, weekend: any, holidays:
4522
4522
  * @returns
4523
4523
  */
4524
4524
  export function XIRR(values: any, dates: any, guess: any): any;
4525
- export function XLOOKUP(lookup_value: any, lookup_array: any, return_array: any, if_not_found: any, match_mode: any, search_mode: any): any;
4525
+ export function XLOOKUP(search_key: any, lookup_range: any, result_range: any, missing_value: any, isCol: any, match_mode: any, search_mode: any): any;
4526
4526
  /**
4527
4527
  * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
4528
4528
  *