I've come across a very interesting - yet confusing - code snippet and had hard time to understand what exactly does it return it.
// Create a data point generator.
var getDataPoint = (function() {
var _x = -1;
var _max = _data.length;
return function() {
_x = (_x + 1) % _max;
return {
x: Date.now(),
y: _data[_x]
};
};
})();
var heartRate = 60; // bpm
var interval = 60 * 1000 / (_data.length * heartRate);
// Generate a new data point based on the heart rate.
setInterval(function() {
$('.jke-ecgChart').ecgChart('addDataPoint', getDataPoint());
}, interval);
Now I have a very basic understanding of closures and how they work, for example, they're scope within outer functions.
But what confused me more is this specific line:
$('.jke-ecgChart').ecgChart('addDataPoint', getDataPoint());
What will getDataPoint() return? A function or {x, y}?
What if I wanted to return {x, y} instead of the function?
Thanks
return function() {...};wouldn't return a function? If you want to return a value, just return the value.