form0-core 0.3.0 → 0.4.0

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.
Files changed (60) hide show
  1. package/README.md +63 -0
  2. package/package.json +5 -2
  3. package/src/builtins/builtin-definitions.js +320 -0
  4. package/src/builtins/choice/choicelabel.js +2 -17
  5. package/src/builtins/choice/choicelabels.js +2 -17
  6. package/src/builtins/choice/choicevalue.js +2 -20
  7. package/src/builtins/choice/choicevalues.js +2 -17
  8. package/src/builtins/choice/hasother.js +2 -20
  9. package/src/builtins/choice/other.js +2 -20
  10. package/src/builtins/control/eval.js +78 -31
  11. package/src/builtins/control/setresult.js +29 -17
  12. package/src/builtins/date/dateadd.js +24 -0
  13. package/src/builtins/date/days.js +22 -0
  14. package/src/builtins/event/control/off.js +3 -27
  15. package/src/builtins/event/control/on.js +3 -19
  16. package/src/builtins/event/event-operations-collector.js +33 -9
  17. package/src/builtins/event/field/setvalue.js +3 -32
  18. package/src/builtins/event/ui/alert.js +3 -11
  19. package/src/builtins/logical/and.js +2 -17
  20. package/src/builtins/logical/array.js +2 -35
  21. package/src/builtins/logical/count.js +2 -20
  22. package/src/builtins/logical/counta.js +2 -20
  23. package/src/builtins/logical/countblank.js +2 -20
  24. package/src/builtins/logical/if.js +2 -20
  25. package/src/builtins/logical/or.js +2 -17
  26. package/src/builtins/math/abs.js +2 -20
  27. package/src/builtins/math/ceiling.js +2 -20
  28. package/src/builtins/math/cos.js +2 -20
  29. package/src/builtins/math/round.js +2 -23
  30. package/src/builtins/math/sin.js +2 -20
  31. package/src/builtins/registry.js +23 -40
  32. package/src/builtins/schema/datanames.js +9 -20
  33. package/src/builtins/schema/form.js +2 -20
  34. package/src/builtins/string/upper.js +2 -20
  35. package/src/engine/calculation-diagnostics.js +107 -0
  36. package/src/engine/calculation.js +65 -32
  37. package/src/engine/conditions.js +69 -3
  38. package/src/engine/evaluator.js +56 -18
  39. package/src/engine/event-operation-scope.js +61 -0
  40. package/src/engine/event-source.js +164 -0
  41. package/src/engine/events.js +111 -23
  42. package/src/engine/form-engine.js +61 -16
  43. package/src/engine/warning-system.js +7 -5
  44. package/src/schema/field-specs.js +2 -2
  45. package/src/security/validation.js +10 -8
  46. package/src/utilities/calculation-editor.js +42 -6
  47. package/src/utilities/date-utils.js +72 -0
  48. package/src/builtins/docs/choice/choicelabel.mdx +0 -110
  49. package/src/builtins/docs/choice/choicelabels.mdx +0 -230
  50. package/src/builtins/docs/choice/choicevalue.mdx +0 -109
  51. package/src/builtins/docs/choice/choicevalues.mdx +0 -196
  52. package/src/builtins/docs/choice/hasother.mdx +0 -133
  53. package/src/builtins/docs/choice/other.mdx +0 -150
  54. package/src/builtins/docs/control/setresult.mdx +0 -203
  55. package/src/builtins/docs/event/field/setvalue.mdx +0 -239
  56. package/src/builtins/docs/index.mdx +0 -234
  57. package/src/builtins/docs/logical/and.mdx +0 -141
  58. package/src/builtins/docs/logical/if.mdx +0 -94
  59. package/src/builtins/docs/logical/or.mdx +0 -191
  60. package/src/builtins/docs/overview.mdx +0 -255
@@ -1,239 +0,0 @@
1
- ---
2
- title: "SETVALUE Builtin"
3
- description: "Set field values in form0 event contexts"
4
- category: "event"
5
- tags: ["event", "field", "value", "manipulation"]
6
- ---
7
-
8
- # SETVALUE Function
9
-
10
- The `SETVALUE` builtin sets a field value within event context, automatically collecting the operation for platform execution. This function supports multiple field types including TextField, NumericField, SingleChoiceField, and MultiChoiceField.
11
-
12
- ## Syntax
13
-
14
- ```javascript
15
- SETVALUE('field_dataname', value)
16
- ```
17
-
18
- ## Parameters
19
-
20
- | Parameter | Type | Description |
21
- |-----------|------|-------------|
22
- | `fieldDataName` | `string` | The data name of the field to set |
23
- | `valueToSet` | `any` | The value to set (string, number, array, etc.) |
24
-
25
- ## Return Value
26
-
27
- Returns an operation descriptor for platform execution (for backward compatibility), while internally collecting the operation for automatic execution.
28
-
29
- ## Examples
30
-
31
- ### TextField Value
32
-
33
- ```javascript
34
- // Set text field value
35
- SETVALUE('field_dataname', 'value_to_set')
36
- ```
37
-
38
- ### NumericField Value
39
-
40
- ```javascript
41
- // Set numeric field value
42
- SETVALUE('field_dataname', 12)
43
- ```
44
-
45
- ### SingleChoiceField Value
46
-
47
- ```javascript
48
- // Set single choice field value
49
- SETVALUE('field_dataname', 'choicefield_value_to_set')
50
- ```
51
-
52
- ### MultiChoiceField Value
53
-
54
- ```javascript
55
- // Set multiple choice field value
56
- SETVALUE('field_dataname', ['value1', 'value2', 'value3'])
57
- ```
58
-
59
- ### Conditional Value Setting
60
-
61
- ```javascript
62
- // Set field value based on condition
63
- SETVALUE('discount_field', IF(user.isPremium, 20, 10))
64
- ```
65
-
66
- ### Dynamic Value Setting
67
-
68
- ```javascript
69
- // Set field value based on other fields
70
- SETVALUE('full_name', firstName + " " + lastName)
71
- ```
72
-
73
- ## Field Type Compatibility
74
-
75
- The `SETVALUE` function supports different value formats for different field types:
76
-
77
- | Field Type | Value Format | Example |
78
- |------------|-------------|---------|
79
- | `TextField` | String | `'text value'` |
80
- | `NumericField` | Number | `42` or `3.14` |
81
- | `SingleChoiceField` | String choice value | `'option1'` |
82
- | `MultiChoiceField` | Array of strings | `['option1', 'option2']` |
83
-
84
- ## How It Works
85
-
86
- 1. **Operation Creation**: Creates a field operation descriptor with type 'FIELD_OPERATION'
87
- 2. **Operation Collection**: Uses `__collectEventOperation` to collect the operation
88
- 3. **Platform Execution**: The platform retrieves and executes collected operations
89
- 4. **Value Formatting**: The platform handles appropriate value formatting for each field type
90
- 5. **Field Update**: The field value is updated in the form state
91
-
92
- ## Common Use Cases
93
-
94
- - **Field auto-population**: Setting field values based on other field changes
95
- - **Form validation responses**: Setting fields based on validation results
96
- - **Business rule applications**: Applying complex business logic to field values
97
- - **User interaction responses**: Updating fields based on user actions
98
- - **Data calculations**: Setting calculated values in fields
99
- - **Conditional field updates**: Setting different values based on conditions
100
-
101
- ## Best Practices
102
-
103
- 1. **Use correct field data names**: Ensure the field data name exists in your form
104
- 2. **Match field types**: Use appropriate value formats for each field type
105
- 3. **Handle null/undefined**: Consider edge cases in your value assignments
106
- 4. **Event context only**: This function is only available in event contexts
107
- 5. **Platform dependency**: The actual field update depends on platform implementation
108
-
109
- ## Important Notes
110
-
111
- - **Event context only**: This builtin is only available in event contexts, not in calculations
112
- - **Platform execution**: The actual field value setting is handled by the platform
113
- - **Operation collection**: Operations are automatically collected and executed
114
- - **Type handling**: The platform handles value formatting for different field types
115
- - **Asynchronous execution**: Field updates may occur asynchronously after event completion
116
-
117
- ## Related Functions
118
-
119
- - [`ALERT`](../ui/alert.mdx) - Display alert messages in event contexts
120
- - [`IF`](../../logical/if.mdx) - Conditional logic for value selection
121
- - [`AND`](../../logical/and.mdx) - Multiple condition checks
122
- - [`OR`](../../logical/or.mdx) - Alternative condition checks
123
-
124
- ## Examples by Use Case
125
-
126
- ### Auto-calculation Fields
127
-
128
- ```javascript
129
- // Calculate and set total price
130
- SETVALUE('total_price', price * quantity * (1 + taxRate))
131
- ```
132
-
133
- ### Form Validation Responses
134
-
135
- ```javascript
136
- // Set error message field based on validation
137
- SETVALUE('error_message',
138
- IF(email.isValid, '', 'Please enter a valid email address')
139
- )
140
- ```
141
-
142
- ### User Type Based Updates
143
-
144
- ```javascript
145
- // Set discount based on user type
146
- SETVALUE('discount_amount',
147
- IF(user.isPremium, orderTotal * 0.2, orderTotal * 0.05)
148
- )
149
- ```
150
-
151
- ### Multi-field Calculations
152
-
153
- ```javascript
154
- // Calculate and set BMI
155
- SETVALUE('bmi', weight / (height * height))
156
- ```
157
-
158
- ### Choice Field Updates
159
-
160
- ```javascript
161
- // Set available options based on category
162
- SETVALUE('subcategory_options',
163
- IF(category === 'electronics',
164
- ['phone', 'laptop', 'tablet'],
165
- ['shirt', 'pants', 'shoes']
166
- )
167
- )
168
- ```
169
-
170
- ### Data Aggregation
171
-
172
- ```javascript
173
- // Set summary field
174
- SETVALUE('order_summary',
175
- 'Items: ' + itemCount + ', Total: $' + totalAmount
176
- )
177
- ```
178
-
179
- ## Advanced Examples
180
-
181
- ### Complex Business Logic
182
-
183
- ```javascript
184
- // Calculate shipping cost with multiple factors
185
- SETVALUE('shipping_cost',
186
- IF(country === "US",
187
- IF(orderValue > 50, 0, 5.99),
188
- IF(orderValue > 100, 10, 15.99)
189
- )
190
- )
191
- ```
192
-
193
- ### Multi-step Field Updates
194
-
195
- ```javascript
196
- // Update multiple related fields
197
- SETVALUE('first_name', extractedFirstName)
198
- SETVALUE('last_name', extractedLastName)
199
- SETVALUE('full_name', extractedFirstName + " " + extractedLastName)
200
- ```
201
-
202
- ### Conditional Multi-choice Updates
203
-
204
- ```javascript
205
- // Set permissions based on user role
206
- SETVALUE('user_permissions',
207
- IF(userRole === 'admin',
208
- ['read', 'write', 'delete', 'admin'],
209
- IF(userRole === 'editor',
210
- ['read', 'write'],
211
- ['read']
212
- )
213
- )
214
- )
215
- ```
216
-
217
- ### Dynamic Field Population
218
-
219
- ```javascript
220
- // Set field based on external data
221
- SETVALUE('user_profile',
222
- IF(userId.length > 0,
223
- lookupUserProfile(userId),
224
- 'No user selected'
225
- )
226
- )
227
- ```
228
-
229
- ### Form State Management
230
-
231
- ```javascript
232
- // Update form status field
233
- SETVALUE('form_status',
234
- IF(allFieldsValid,
235
- 'ready_for_submission',
236
- 'incomplete'
237
- )
238
- )
239
- ```
@@ -1,234 +0,0 @@
1
- ---
2
- title: "form0 Builtins Documentation"
3
- description: "Complete reference for all form0 builtin functions"
4
- category: "index"
5
- tags: ["documentation", "reference", "builtins"]
6
- ---
7
-
8
- # form0 Builtins Documentation
9
-
10
- Welcome to the complete reference for form0 builtin functions. This documentation covers all available functions, their usage, and practical examples.
11
-
12
- ## Getting Started
13
-
14
- - **[Overview](./overview.mdx)** - Introduction to the builtins system
15
- - **[Quick Reference](#quick-reference)** - Function summary table
16
- - **[Common Patterns](#common-patterns)** - Frequently used combinations
17
-
18
- ## Logical Functions
19
-
20
- Essential functions for conditional logic and boolean operations:
21
-
22
- | Function | Description | Use Cases |
23
- |----------|-------------|-----------|
24
- | **[IF](../logical/if.mdx)** | Conditional logic and branching | Field visibility, dynamic values, validation messages |
25
- | **[AND](../logical/and.mdx)** | Logical AND operations | Multi-condition validation, permission checks |
26
- | **[OR](../logical/or.mdx)** | Logical OR operations | Alternative requirements, fallback logic |
27
-
28
- ## Control Functions
29
-
30
- Functions for managing calculation flow and results:
31
-
32
- | Function | Description | Use Cases |
33
- |----------|-------------|-----------|
34
- | **[SETRESULT](../control/setresult.mdx)** | Set calculation results | Price calculations, score computations, field aggregations |
35
-
36
- ## Quick Reference
37
-
38
- ### IF Function
39
-
40
- ```javascript
41
- IF(condition, trueValue, falseValue)
42
- ```
43
-
44
- **Common Usage:**
45
- - Field visibility: `IF(user.isPremium, true, false)`
46
- - Dynamic pricing: `IF(quantity > 10, price * 0.9, price)`
47
- - Validation messages: `IF(age < 18, "Must be 18+", "")`
48
-
49
- ### AND Function
50
-
51
- ```javascript
52
- AND(...conditions)
53
- ```
54
-
55
- **Common Usage:**
56
- - Form validation: `AND(email.isValid, phone.isValid, name.length > 0)`
57
- - Permission checks: `AND(user.isLoggedIn, user.hasPermission)`
58
- - Business rules: `AND(inStock, paymentValid, addressComplete)`
59
-
60
- ### OR Function
61
-
62
- ```javascript
63
- OR(...conditions)
64
- ```
65
-
66
- **Common Usage:**
67
- - Alternative requirements: `OR(email.length > 0, phone.length > 0)`
68
- - Feature detection: `OR(user.isPremium, user.isVip, user.hasSubscription)`
69
- - Fallback logic: `OR(user.preferredName, user.firstName, "Guest")`
70
-
71
- ### SETRESULT Function
72
-
73
- ```javascript
74
- SETRESULT(value)
75
- ```
76
-
77
- **Common Usage:**
78
- - Price calculations: `SETRESULT(price * quantity * (1 + taxRate))`
79
- - Score computations: `SETRESULT((score1 + score2 + score3) / 3)`
80
- - Conditional results: `SETRESULT(IF(eligible, amount, 0))`
81
-
82
- ## Common Patterns
83
-
84
- ### Complex Conditional Logic
85
-
86
- ```javascript
87
- // Multi-level pricing
88
- IF(user.type === "premium",
89
- IF(order.value > 100, "free-shipping", "discounted-shipping"),
90
- IF(order.value > 50, "reduced-shipping", "standard-shipping")
91
- )
92
- ```
93
-
94
- ### Validation Chains
95
-
96
- ```javascript
97
- // Comprehensive form validation
98
- AND(
99
- email.includes("@"),
100
- phone.length >= 10,
101
- age >= 18,
102
- OR(hasLicense, hasAlternateId),
103
- agreedToTerms === true
104
- )
105
- ```
106
-
107
- ### Calculation Pipelines
108
-
109
- ```javascript
110
- // Complex business calculation
111
- SETRESULT(
112
- (basePrice * quantity) *
113
- IF(user.isPremium, 0.9, 1.0) *
114
- IF(location === "remote", 1.1, 1.0) +
115
- IF(AND(urgent, businessHours), 25, 0)
116
- )
117
- ```
118
-
119
- ### Dynamic Field Behavior
120
-
121
- ```javascript
122
- // Show field based on multiple conditions
123
- IF(AND(user.role === "admin", feature.enabled, environment === "production"),
124
- "visible",
125
- "hidden"
126
- )
127
- ```
128
-
129
- ## Function Combinations
130
-
131
- ### IF + AND
132
-
133
- ```javascript
134
- // Show premium features only when all conditions are met
135
- IF(AND(user.isPremium, feature.enabled, user.region === "US"),
136
- premiumContent,
137
- standardContent
138
- )
139
- ```
140
-
141
- ### IF + OR
142
-
143
- ```javascript
144
- // Apply discount if user has any qualifying status
145
- IF(OR(user.isStudent, user.isSenior, user.isMilitary),
146
- discountedPrice,
147
- regularPrice
148
- )
149
- ```
150
-
151
- ### AND + OR
152
-
153
- ```javascript
154
- // Complex eligibility check
155
- AND(
156
- age >= 18,
157
- OR(hasDriversLicense, hasStateId, hasPassport),
158
- OR(hasProofOfIncome, hasGuarantor)
159
- )
160
- ```
161
-
162
- ### Nested Functions
163
-
164
- ```javascript
165
- // Sophisticated business logic
166
- SETRESULT(
167
- IF(AND(user.isVip, order.value > 500),
168
- IF(OR(user.country === "US", user.country === "CA"),
169
- 0, // Free shipping for VIP in North America
170
- 10 // Reduced shipping for VIP elsewhere
171
- ),
172
- IF(order.value > 100,
173
- 5, // Standard reduced shipping
174
- 15 // Regular shipping
175
- )
176
- )
177
- )
178
- ```
179
-
180
- ## Best Practices
181
-
182
- 1. **Keep expressions readable** - Break complex logic into smaller parts
183
- 2. **Use descriptive field names** - Make your conditions self-documenting
184
- 3. **Handle edge cases** - Consider null/undefined values
185
- 4. **Test thoroughly** - Verify all code paths work as expected
186
- 5. **Document complex logic** - Add comments for maintainability
187
-
188
- ## Performance Tips
189
-
190
- - **Order conditions by likelihood** - Put most likely conditions first
191
- - **Use short-circuit evaluation** - `AND` and `OR` stop early when possible
192
- - **Avoid deeply nested expressions** - Consider splitting complex logic
193
- - **Cache expensive operations** - Don't repeat the same calculations
194
-
195
- ## Troubleshooting
196
-
197
- ### Common Issues
198
-
199
- 1. **Undefined values** - Use `OR` for fallbacks: `OR(user.name, "Unknown")`
200
- 2. **Type mismatches** - Ensure consistent data types in comparisons
201
- 3. **Logic errors** - Test all branches of conditional statements
202
- 4. **Performance** - Avoid excessive nesting and complex expressions
203
-
204
- ### Debugging Tips
205
-
206
- - Use simple test cases to verify function behavior
207
- - Break complex expressions into smaller parts
208
- - Check that all required fields are available
209
- - Verify data types match expectations
210
-
211
- ## Examples by Domain
212
-
213
- ### E-commerce
214
- - [Product pricing](../examples/ecommerce.mdx#pricing)
215
- - [Shipping calculations](../examples/ecommerce.mdx#shipping)
216
- - [Discount logic](../examples/ecommerce.mdx#discounts)
217
-
218
- ### User Management
219
- - [Registration validation](../examples/user-management.mdx#registration)
220
- - [Permission checks](../examples/user-management.mdx#permissions)
221
- - [Profile completion](../examples/user-management.mdx#profiles)
222
-
223
- ### Financial Services
224
- - [Loan eligibility](../examples/financial.mdx#loans)
225
- - [Risk assessment](../examples/financial.mdx#risk)
226
- - [Fee calculations](../examples/financial.mdx#fees)
227
-
228
- ## Support
229
-
230
- For questions or issues:
231
- - Check the [form0 documentation](https://form0.dev/docs)
232
- - Review [common patterns](#common-patterns) above
233
- - See [troubleshooting](#troubleshooting) section
234
- - Visit the [form0 GitHub repository](https://github.com/form0-dev/form0-core)
@@ -1,141 +0,0 @@
1
- ---
2
- title: "AND Builtin"
3
- description: "Logical AND operation for form0 expressions"
4
- category: "logical"
5
- tags: ["logical", "boolean", "validation"]
6
- ---
7
-
8
- # AND Function
9
-
10
- The `AND` builtin performs logical AND operations, returning `true` only when all provided arguments are truthy.
11
-
12
- ## Syntax
13
-
14
- ```javascript
15
- AND(...args)
16
- ```
17
-
18
- ## Parameters
19
-
20
- | Parameter | Type | Description |
21
- |-----------|------|-------------|
22
- | `...args` | `any` | Any number of arguments to evaluate |
23
-
24
- ## Return Value
25
-
26
- Returns `true` if all arguments are truthy, `false` otherwise.
27
-
28
- ## Examples
29
-
30
- ### Basic Usage
31
-
32
- ```javascript
33
- // Check if user meets multiple criteria
34
- AND(user.age >= 18, user.hasEmail, user.agreedToTerms)
35
- ```
36
-
37
- ### Form Validation
38
-
39
- ```javascript
40
- // Validate required fields
41
- AND(name.length > 0, email.includes("@"), phone.length >= 10)
42
- ```
43
-
44
- ### Complex Conditions
45
-
46
- ```javascript
47
- // Check multiple business rules
48
- AND(
49
- order.amount > 0,
50
- inventory.stock >= order.quantity,
51
- customer.creditScore > 600,
52
- customer.accountStatus === "active"
53
- )
54
- ```
55
-
56
- ### Field Dependencies
57
-
58
- ```javascript
59
- // Show field only when multiple conditions are met
60
- AND(showAdvanced, user.role === "admin", feature.enabled)
61
- ```
62
-
63
- ### Nested with Other Functions
64
-
65
- ```javascript
66
- // Combine with IF for complex logic
67
- IF(AND(user.isPremium, order.value > 100), "Free shipping", "Standard shipping")
68
- ```
69
-
70
- ## Truthiness Rules
71
-
72
- The `AND` function uses JavaScript's standard truthiness evaluation:
73
-
74
- **Falsy values:**
75
- - `false`
76
- - `0`
77
- - `""` (empty string)
78
- - `null`
79
- - `undefined`
80
- - `NaN`
81
-
82
- **Truthy values:**
83
- - `true`
84
- - Any non-zero number
85
- - Any non-empty string
86
- - Objects and arrays
87
- - Functions
88
-
89
- ## Common Use Cases
90
-
91
- - **Form validation**: Ensure multiple fields are properly filled
92
- - **User permissions**: Check if user has multiple required permissions
93
- - **Business rules**: Validate complex business logic conditions
94
- - **Feature flags**: Enable features when multiple conditions are met
95
- - **Data integrity**: Ensure data meets multiple criteria
96
-
97
- ## Best Practices
98
-
99
- 1. **Order by likelihood**: Put most likely-to-fail conditions first for better performance
100
- 2. **Use descriptive expressions**: Make conditions self-documenting
101
- 3. **Limit complexity**: Too many conditions can be hard to debug
102
- 4. **Consider short-circuiting**: `AND` stops evaluating once it finds a falsy value
103
-
104
- ## Performance Notes
105
-
106
- - **Short-circuit evaluation**: Stops checking as soon as a falsy value is found
107
- - **Evaluation order**: Arguments are evaluated left to right
108
- - **Lazy evaluation**: Later arguments won't be evaluated if earlier ones are falsy
109
-
110
- ## Related Functions
111
-
112
- - [`OR`](./or.mdx) - Logical OR operations
113
- - [`IF`](./if.mdx) - Conditional logic
114
-
115
- ## Examples by Use Case
116
-
117
- ### User Authentication
118
-
119
- ```javascript
120
- // Check if user is authenticated and authorized
121
- AND(user.isLoggedIn, user.permissions.includes("read"), user.sessionValid)
122
- ```
123
-
124
- ### E-commerce Validation
125
-
126
- ```javascript
127
- // Validate order can be processed
128
- AND(
129
- product.inStock,
130
- customer.paymentMethodValid,
131
- shippingAddress.isComplete,
132
- order.total > 0
133
- )
134
- ```
135
-
136
- ### Feature Gating
137
-
138
- ```javascript
139
- // Enable beta feature
140
- AND(user.betaOptIn, feature.betaEnabled, environment === "production")
141
- ```
@@ -1,94 +0,0 @@
1
- ---
2
- title: "IF Builtin"
3
- description: "Conditional logic function for form0 expressions"
4
- category: "logical"
5
- tags: ["conditional", "logic", "branching"]
6
- ---
7
-
8
- # IF Function
9
-
10
- The `IF` builtin provides conditional logic within form0 expressions, allowing you to return different values based on a condition.
11
-
12
- ## Syntax
13
-
14
- ```javascript
15
- IF(condition, trueValue, falseValue)
16
- ```
17
-
18
- ## Parameters
19
-
20
- | Parameter | Type | Description |
21
- |-----------|------|-------------|
22
- | `condition` | `boolean` | The condition to evaluate |
23
- | `trueValue` | `any` | Value returned when condition is true |
24
- | `falseValue` | `any` | Value returned when condition is false |
25
-
26
- ## Return Value
27
-
28
- Returns `trueValue` if the condition is truthy, otherwise returns `falseValue`.
29
-
30
- ## Examples
31
-
32
- ### Basic Usage
33
-
34
- ```javascript
35
- // Show discount message based on user status
36
- IF(user.isPremium, "20% off", "No discount")
37
- ```
38
-
39
- ### Numeric Calculations
40
-
41
- ```javascript
42
- // Apply different tax rates
43
- IF(country === "US", price * 0.08, price * 0.20)
44
- ```
45
-
46
- ### Nested Conditions
47
-
48
- ```javascript
49
- // Determine shipping cost based on location and order value
50
- IF(country === "US",
51
- IF(orderValue > 50, 0, 5.99),
52
- IF(orderValue > 100, 10, 15.99)
53
- )
54
- ```
55
-
56
- ### Field Visibility
57
-
58
- ```javascript
59
- // Show additional fields for premium users
60
- IF(user.type === "premium", true, false)
61
- ```
62
-
63
- ### Dynamic Form Validation
64
-
65
- ```javascript
66
- // Conditional validation messages
67
- IF(age < 18, "Must be 18 or older", "")
68
- ```
69
-
70
- ## Common Use Cases
71
-
72
- - **Conditional pricing**: Different prices based on user type or location
73
- - **Dynamic field visibility**: Show/hide fields based on other field values
74
- - **Validation messages**: Display different error messages based on conditions
75
- - **User experience**: Personalize content based on user preferences
76
- - **Business logic**: Implement complex conditional rules
77
-
78
- ## Best Practices
79
-
80
- 1. **Keep conditions simple**: Complex conditions can be hard to read and debug
81
- 2. **Use descriptive variable names**: Make your conditions self-documenting
82
- 3. **Consider nested IFs carefully**: Too many levels can become difficult to maintain
83
- 4. **Test edge cases**: Ensure your conditions handle all possible scenarios
84
-
85
- ## Related Functions
86
-
87
- - [`AND`](./and.mdx) - Logical AND operations
88
- - [`OR`](./or.mdx) - Logical OR operations
89
-
90
- ## Notes
91
-
92
- - The condition is evaluated using JavaScript's truthiness rules
93
- - Both `trueValue` and `falseValue` can be of any type
94
- - The function is lazy-evaluated - only the returned branch is computed