https://github.com/kylejeske/ts-calculator-anoymous-closurers
Example of a calculator which uses a closure design, within an anonymous method, for a private context not accessible from the scope of the public methods.
https://github.com/kylejeske/ts-calculator-anoymous-closurers
closures es6-javascript typescript
Last synced: 4 months ago
JSON representation
Example of a calculator which uses a closure design, within an anonymous method, for a private context not accessible from the scope of the public methods.
- Host: GitHub
- URL: https://github.com/kylejeske/ts-calculator-anoymous-closurers
- Owner: kylejeske
- Created: 2021-02-17T15:11:02.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2021-02-17T20:16:55.000Z (over 4 years ago)
- Last Synced: 2025-02-08T10:24:50.376Z (8 months ago)
- Topics: closures, es6-javascript, typescript
- Language: TypeScript
- Homepage:
- Size: 6.84 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Code of conduct: .github/CODE_OF_CONDUCT.md
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
# Private Context Value within Public Calculator
## Purpose
Show how to use a private scope context within an annoymous function. So we can access
public methods (`add, subtract, total`) but keep the running value (`privateContext`) seperated.### Interface: CalculatorDesign
```ts
interface CalculatorDesign {
add(value: number): number;
subtract(value: number): number;
total(): number;
}
```### Class Implementation: Calculator
```ts
const Calculator = () => {// Private Scope
let privateContext = 0;// Calculator implementing Design Interface
return new class Calculator implements CalculatorDesign {
constructor(private context: number = privateContext) {
// empty
}
total(): number {
return this.context;
}
add(value: number): number {
this.context += value;
return this.context;
}
subtract(value: number): number {
this.context -= value;
return this.context;
}
};
};
```### Execution
```ts
import Calculator from "./calculator";/**
* Public Methods: add, substract, total
*/
const calc = Calculator();calc.add(10);
calc.subtract(10);// get our total
const total = calc.total(); // 10```
## Testing
- Run Unit Tests against the Calculator module.
```bash
calculate
✓ should not contain 'context' as part of the prototype scope
✓ should contain functions 'add, substract, total' as part of the prototype scope
✓ should return zero at first
✓ should return 10 after adding 104 passing (25ms)
```