- From: Rick Waldron via GitHub <sysbot+gh@w3.org>
- Date: Mon, 18 Sep 2017 18:29:23 +0000
- To: public-device-apis-log@w3.org
Hey @kenchris, though I'm not sure web API specs should be bending for third party tools, I believe your original post is interesting and worth exploring. That said, I had to admit that my TypeScript is about 4 to 5 years out of date (I haven't spent much time with it since it was originally released). I reached out to a trusted advisor, in a manner of speaking, and @brianloveswords was able to shed some interesting light on the example and in the form of a possible TS-friendly solution. We had to make a few assumptions about the goals of your program, based on the snippet provided. Hopefully we captured the spirit enough for our proposed solution to be viable and valuable.
```ts
interface ReadXYZSensor {
readonly timestamp: number;
readonly x: number;
readonly y: number;
readonly z: number;
}
interface UnreadXYZSensor {
readonly timestamp: undefined;
readonly x: undefined;
readonly y: undefined;
readonly z: undefined;
}
type XYZSensor = ReadXYZSensor | UnreadXYZSensor;
function sensorHasData(sensor: XYZSensor): sensor is ReadXYZSensor {
// it's possible to use a check against any property of the sensor
// as being defined for a test to see whether the sensor is read
// or unread since a sensor exists in one of two states: either
// every property is undefined or all of them have values
return !!sensor.timestamp;
}
class Filter {
constructor(
public x: number,
public y: number,
public z: number,
public timestamp: number,
public cutoff: number,
) { }
public update(reading: XYZSensor) {
if (!sensorHasData(reading)) {
return;
}
if (!sensorHasData(this as XYZSensor)) {
this.x = reading.x;
this.y = reading.y;
this.z = reading.z;
this.timestamp = reading.timestamp;
return;
}
const dt = reading.timestamp - this.timestamp / 1000;
this.timestamp = reading.timestamp;
const alpha = this.cutoff / (this.cutoff + dt);
this.x = this.x + alpha * (reading.x - this.x);
this.y = this.y + alpha * (reading.y - this.y);
this.z = this.z + alpha * (reading.z - this.z);
}
}
```
(This was written and type checked against TypeScript 2.5.2)
--
GitHub Notification of comment by rwaldron
Please view or discuss this issue at https://github.com/w3c/sensors/issues/269#issuecomment-330314492 using your GitHub account
Received on Monday, 18 September 2017 18:29:16 UTC