Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const { multi, method, fromMulti } = require('@arrows/multimethod')
const baseArea = multi(
(shape) => shape.type,
method('rectangle', (shape) => shape.a * shape.b),
method('square', (shape) => shape.a ** 2),
)
/**
* Creating a new multimethod with many new methods via `fromMulti` function
*/
const area = fromMulti(
method('circle', (shape) => Math.PI * shape.r ** 2),
method('triangle', (shape) => 0.5 * shape.a * shape.h),
)(baseArea)
console.log(
area({ type: 'square', a: 5 }), // -> 25
area({ type: 'circle', r: 3 }), // -> 28.274333882308138
)
const { multi, method, fromMulti } = require('@arrows/multimethod')
/**
* Function where the priority does matter
*
* @param {number} points
* @returns {number} grade
*/
const baseGradeExam = multi(
method((points) => points < 10, 'failed'),
method((points) => points <= 15, 'ok'),
method((points) => points > 15, 'good'),
)
const gradeExam = fromMulti(
method((points) => points === 0, 'terrible'),
method((points) => points > 20, 'excellent'),
)(baseGradeExam)
console.log(
gradeExam(0), // -> 'terrible'
gradeExam(5), // -> 'failed'
gradeExam(10), // -> 'ok'
gradeExam(15), // -> 'ok'
gradeExam(20), // -> 'good'
gradeExam(25), // -> 'excellent'
)
const data = { name: 'Alice', score: 100 }
save(data, 'json') // -> "Saving as JSON!"
save(data, 'html') // -> "Saving as HTML!"
save(data, 'csv') // -> "Default - saving as TXT!"
const extendedSave = method('csv', (data, format) => {
console.log('Saving as CSV!')
})(save)
extendedSave(data, 'json') // -> "Saving as JSON!"
extendedSave(data, 'html') // -> "Saving as HTML!"
extendedSave(data, 'csv') // -> "Saving as CSV!"
extendedSave(data, 'yaml') // -> "Default - saving as TXT!"
const extendedSave2 = fromMulti(
method('csv', (data, format) => {
console.log('Saving as CSV!')
}),
method('yaml', (data, format) => {
console.log('Saving as YAML!')
}),
)(save)
extendedSave2(data, 'json') // -> "Saving as JSON!"
extendedSave2(data, 'html') // -> "Saving as HTML!"
extendedSave2(data, 'csv') // -> "Saving as CSV!"
extendedSave2(data, 'yaml') // -> "Saving as YAML!"