To create a pipe that performs complex mathematical calculations on input data, you'll need to implement a custom pipe in your framework of choice (Angular, Vue, React, etc.). Here's how to approach this in Angular, which has a built-in pipe system:
1. Create the pipe (math.pipe.ts):
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'math'
})
export class MathPipe implements PipeTransform {
transform(value: number, operation: string, operand?: number): number {
switch(operation) {
case 'add': return value + (operand || 0);
case 'subtract': return value - (operand || 0);
case 'multiply': return value * (operand || 1);
case 'divide': return value / (operand || 1);
case 'square': return value * value;
default: return value;
}
}
}
2. Register the pipe in your module:
Add MathPipe to the declarations array in your Angular module.
3. Use it in a template:
<p>5 + 3 = {{ 5 | math:'add':3 }}</p> <!-- Output: 8 -->
<p>10 - 4 = {{ 10 | math:'subtract':4 }}</p> <!-- Output: 6 -->
<p>6 × 2 = {{ 6 | math:'multiply':2 }}</p> <!-- Output: 12 -->
<p>8 ÷ 2 = {{ 8 | math:'divide':2 }}</p> <!-- Output: 4 -->
<p>5² = {{ 5 | math:'square' }}</p> <!-- Output: 25 -->