Skip to content

Commit 30de4ab

Browse files
authored
docs: document usage of the concat operator | (#11)
* docs: document usage of the concat operator |
1 parent 37e2933 commit 30de4ab

1 file changed

Lines changed: 37 additions & 1 deletion

File tree

docs/syntax.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ The parser accepts a pretty basic grammar. It's similar to normal JavaScript exp
1212
| ^ | Right | Exponentiation |
1313
| +, -, not, sqrt, etc. | Right | Unary prefix operators (see below for the full list) |
1414
| \*, /, % | Left | Multiplication, division, remainder |
15-
| +, -, \|\| | Left | Addition, subtraction, array/list concatenation |
15+
| +, -, \| | Left | Addition, subtraction, array/string concatenation |
1616
| ==, !=, >=, <=, >, <, in | Left | Equals, not equals, etc. "in" means "is the left operand included in the right array operand?" |
1717
| and | Left | Logical AND |
1818
| or | Left | Logical OR |
@@ -30,6 +30,42 @@ const parser = new Parser({
3030
// Now parser supports 'x in array' and 'y = 2*x' expressions
3131
```
3232

33+
## Concatenation Operator
34+
35+
The `|` (pipe) operator concatenates arrays or strings:
36+
- If both operands are arrays, they are concatenated as arrays
37+
- If both operands are strings, they are concatenated as strings
38+
- If operands are of different types, the result is `undefined`
39+
40+
| Operator | Description |
41+
|:-------- |:----------- |
42+
| a \| b | Concatenates `a` and `b` if both are arrays or both are strings; otherwise returns `undefined`. |
43+
44+
### Array Concatenation
45+
46+
When both operands are arrays, the `|` operator returns a new array containing all elements from both arrays:
47+
48+
```js
49+
const parser = new Parser();
50+
51+
parser.evaluate('[1, 2] | [3, 4]'); // [1, 2, 3, 4]
52+
parser.evaluate('[1] | [2] | [3]'); // [1, 2, 3]
53+
parser.evaluate('["a", "b"] | ["c", "d"]'); // ["a", "b", "c", "d"]
54+
```
55+
56+
### String Concatenation
57+
58+
When both operands are strings, the `|` operator returns a new string combining both:
59+
60+
```js
61+
const parser = new Parser();
62+
63+
parser.evaluate('"hello" | " " | "world"'); // "hello world"
64+
parser.evaluate('"a" | "b" | "c"'); // "abc"
65+
```
66+
67+
> **Note:** Mixing types (e.g., an array with a string) will return `undefined`.
68+
3369
## Unary Operators
3470

3571
The parser has several built-in "functions" that are actually unary operators. The primary difference between these and functions are that they can only accept exactly one argument, and parentheses are optional. With parentheses, they have the same precedence as function calls, but without parentheses, they keep their normal precedence (just below `^`). For example, `sin(x)^2` is equivalent to `(sin x)^2`, and `sin x^2` is equivalent to `sin(x^2)`.

0 commit comments

Comments
 (0)