Created
May 24, 2019 19:56
-
-
Save tetsuo/ba6d5525fb61a5964cf1620244e2017b to your computer and use it in GitHub Desktop.
lens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { array } from 'fp-ts/lib/Array' | |
import { fromTraversable, Lens, Prism, Iso } from 'monocle-ts' | |
interface Model { | |
sensors: Array<Sensor> | |
} | |
interface Sensor { | |
ip: string | |
temp: number | |
} | |
// describes a focus into a Model's sensors property | |
const sensorsLens = Lens.fromProp<Model, 'sensors'>('sensors') | |
// describes a focus into a Sensor's temp property | |
const sensorValueLens = Lens.fromProp<Sensor, 'temp'>('temp') | |
// describes an array traversal of Sensor's | |
const sensorTraversal = fromTraversable(array)<Sensor>() | |
// describes a metric x temperature isomorphism | |
const tempToMetric = new Iso<number, number>(temp => temp * 1.8 + 32, metric => (metric - 32) / 1.8) | |
// composite Traversal to access all the given Sensor values | |
const composedTraversal = sensorsLens.composeTraversal(sensorTraversal).composeLens(sensorValueLens) | |
// refinement for hot sensors | |
const isHot = Prism.fromPredicate<number>(x => x > 30) | |
// our test data | |
const data: Model = { | |
sensors: [ | |
{ ip: '192.168.0.1', temp: 1 }, | |
{ ip: '192.168.0.2', temp: 5 }, | |
{ ip: '192.168.0.3', temp: 42 }, | |
{ ip: '192.168.0.2', temp: 6 }, | |
{ ip: '192.168.0.3', temp: 555 } | |
] | |
} | |
// get all values | |
const allValues = composedTraversal.asFold().getAll(data) | |
console.log(allValues) // [ 1, 5, 42, 6, 555 ] | |
// get only hot sensor values | |
const hotSensors = composedTraversal | |
.composePrism(isHot) | |
.asFold() | |
.getAll(data) | |
console.log(hotSensors) // [ 42, 555 ] | |
// get only hot sensor values AS metric | |
const hotSensorsMetrics = composedTraversal | |
.composePrism(isHot) | |
.asFold() | |
.composeIso(tempToMetric) | |
.getAll(data) | |
console.log(hotSensorsMetrics) // [ 107.60000000000001, 1031 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment