Railway-oriented programming helper library
npm install baccano





To use the library, first import it:
In Node:
``javascript`
const { compose, fromUnary, SomeError, Success } = require('baccano')
As ES Module:
`javascript`
import { compose, fromUnary, SomeError, Success } from 'baccano'
On the browser:
`html`
#### Define Errors
Features should not be the only things to be considered when planning software. Errors, or anything that can go wrong should also be planned. Hence, we have to define the possible errors that might occur in a particular pipeline of functions. Normally we'd use a type or a variant for this but we're in JavaScript so I suggest using Symbols for them. We'll be using division in the pipeline so we have to plan for a division by zero case.
`javascript`
const DIVISON_BY_ZERO = Symbol.for('DIVISION_BY_ZERO')
`javascript`
import { SomeError, Success } from 'baccano'
After importing our helper functions, let's define the functions we're going to use.
`javascript
const divideBy = n => x => {
if (n === 0) {
return SomeError(DIVISON_BY_ZERO, "Cannot divide by zero.")
} else {
return Success(n / x)
}
}
const plusOne = x => {
return Success(x + 1)
}
`
In this case, we create a function divideBy which takes a number and returns a function that accepts a number and divides it by the previous number. If the previous number is zero, we return a DIVISON_BY_ZERO error using the SomeError function, which takes a value that represents the error and the error message. Else, we return a success using the Success function which accepts a value.
The plusOne function just takes a number and returns a Success with the number incremented by one.
#### Complete Example Code
Here is the complete example code:
`javascript
// Import library
import { compose, fromUnary, SomeError, Success } from 'baccano'
// Define Errors
const DIVISON_BY_ZERO = Symbol.for('DIVISION_BY_ZERO')
const divideBy = n => x => {
if (n === 0) {
return SomeError(DIVISON_BY_ZERO, "Cannot divide by zero.")
} else {
return Success(n / x)
}
}
const plusOne = x => {
return Success(x + 1)
}
(async () => {
// Take unary functions and convert them to compatible functions
const compatibleDivideByZero = fromUnary(divideBy(0))
const compatiblePlusOne = fromUnary(plusOne)
// Create pipeline of functions
const pipeline = compose(compatiblePlusOne, compatibleDivideByZero, compatiblePlusOne)
// Get result of the pipeline
const result = await pipeline(2)
// Display end value
console.log(result.value) // 4
// Display errors
console.log(result.errors) // [ { message: 'Cannot divide by zero.', type: Symbol(DIVISON_BY_ZERO) } ]
})()
``