Reputation: 5085
I'm working on a simple Javascript module and I'd like to make it follow the functional programming style.
This module basically allows you to measure how much time has passed when you started and finished an event and sends the data in chunks of 2 measurements:
const register = {
marks: {},
marksCount: 0,
restart: function () {
this.marks = {}
this.marksCount = 0
},
startMark: function (id) {
performance.mark(`${id}/start`)
},
finishMark: function (id) {
performance.mark(`${id}/end`)
performance.measure(id, `${id}/start`, `${id}/end`)
this.marksCount++
this.marks[id] = performance.getEntriesByName(id, 'measure')[0]
if (this.marksCount === 2) {
console.log(this.marks)
this.restart()
}
}
}
// then you can use it like this
register.startMark('event1')
register.startMark('event2')
register.finishMark('event1')
register.finishMark('event2')
I've been reading some posts regarding how FP manages the state and I'd really like to see how this simple module can be written using pure FP principles, specially how can we prevent mutating the properties.
Upvotes: 0
Views: 87
Reputation: 48775
It's very simple to make an object inaccessible for write. eg.
const storage = v => () => v;
const test = storage(10);
console.log(test()); // prints 10, but you have no way to change v
A functional version of your time measure might look like this:
const startMark = () => {
const start = performance.now();
return () => {
const end = performance.now();
return end - start;
};
}
// How to use
const endMark1 = startMark();
const endMark2 = startMark();
const result1 = endMark1();
const result2 = endMark2();
console.log('time1', result1, 'time2', result2);
// do something else
const result11 = endMark1();
console.log('time1-2', result11);
Since it is functional you can use the endTimer
several times and it will return the time from when it started to now even on consecutive calls.
Upvotes: 2