diff options
author | Nick Van Doorn <vandoorn.nick@gmail.com> | 2018-10-11 00:32:28 -0700 |
---|---|---|
committer | Nick Van Doorn <vandoorn.nick@gmail.com> | 2018-10-11 00:32:28 -0700 |
commit | 7e9c5ec11a712dc05482edd995104c2df2d277f0 (patch) | |
tree | d5b79059fcbed344536d88ccf46e46c698a52b71 | |
parent | 5351d842be4856b9b9f2f4ea8caa05ee1a345eb6 (diff) |
Implement fake data provider
-rw-r--r-- | projects/3-realtime-stocks/src/stock-data.js | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/projects/3-realtime-stocks/src/stock-data.js b/projects/3-realtime-stocks/src/stock-data.js index e69de29..c70e2b4 100644 --- a/projects/3-realtime-stocks/src/stock-data.js +++ b/projects/3-realtime-stocks/src/stock-data.js @@ -0,0 +1,36 @@ +export const generateValue = () => { + const plusOrMinus = Math.round(Math.random()) ? 1 : -1 + return 1 + plusOrMinus * Math.random() * 0.5 +} +export const generateStartingPoints = (n, pollPeriod) => { + return new Array(n).fill(1).map((k, i) => { + return { + value: generateValue(), + datetime: Date.now() - (n - i) * 1000 + } + }) +} +const N_STARTING_POINTS = 50 + +export class StockDataProvider { + constructor() {} + subscribeToStockData(pollFrequency, callback) { + // generate 100 random points + // 15 minutes apart + let points = generateStartingPoints(N_STARTING_POINTS) + const pushCallback = () => { + points.push({ value: generateValue(), datetime: Date.now() }) + points.shift() + callback(points) + } + pushCallback() + const interval = setInterval(pushCallback, pollFrequency) + // give the caller a way to cancel + // the subscription + return { + unsubscribe() { + clearInterval(interval) + } + } + } +} |