Skip to content

Commit

Permalink
Lint and format
Browse files Browse the repository at this point in the history
Signed-off-by: Paz Barda <[email protected]>
  • Loading branch information
pazbardanl committed Jan 18, 2024
1 parent a74b267 commit b1d8cc7
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 123 deletions.
34 changes: 17 additions & 17 deletions src/lib/mock-observations/helpers/CommonGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,29 @@ import {Generator} from '../interfaces';
class CommonGenerator implements Generator {
private name = '';
private generateObject: {} = {};
initialise(name: string, config:{ [key: string]: any }): void {
initialise(name: string, config: {[key: string]: any}): void {
this.name = this.validateName(name);
// TODO PB -- validate config is not null, not empty and a valid yml object, use yaml.parse(input)
// TODO PB -- object immutabilty - copy by value here
this.generateObject = config;
}
}

next(_historical: Object[]): Object {
// TODO PB -- object immutabilty - copy by value here
return this.generateObject
}

public getName(): String {
return this.name;
next(_historical: Object[]): Object {

Check warning on line 13 in src/lib/mock-observations/helpers/CommonGenerator.ts

View workflow job for this annotation

GitHub Actions / build

'_historical' is defined but never used
// TODO PB -- object immutabilty - copy by value here
return this.generateObject;
}

public getName(): String {
return this.name;
}

private validateName(name: string | null): string {
if (name === null || name.trim() === '') {
// TODO PB - custom / more specific error?
throw new Error('name is empty or null');
}

private validateName(name: string | null): string {
if (name === null || name.trim() === '') {
// TODO PB - custom / more specific error?
throw new Error('name is empty or null');
}
return name;
}
return name;
}
}

export default CommonGenerator;
79 changes: 39 additions & 40 deletions src/lib/mock-observations/helpers/RandIntGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,49 @@
import { Generator } from '../interfaces';
import {Generator} from '../interfaces';

class RandIntGenerator implements Generator {
private static readonly MIN: string = 'min';
private static readonly MAX: string = 'max';

private fieldToPopulate: string = '';
private min: number = 0;
private max: number = 0;

initialise(fieldToPopulate: string, config: { [key: string]: any }): void {
private static readonly MIN: string = 'min';
private static readonly MAX: string = 'max';
private fieldToPopulate = '';
private min = 0;
private max = 0;

initialise(fieldToPopulate: string, config: {[key: string]: any}): void {
this.fieldToPopulate = this.validateName(fieldToPopulate);
this.validateConfig(config);
this.min = config[RandIntGenerator.MIN];
this.max = config[RandIntGenerator.MAX];
}
this.validateConfig(config);
this.min = config[RandIntGenerator.MIN];
this.max = config[RandIntGenerator.MAX];
}

next(_historical: Object[]): Object {
const randomNumber = Math.random();
var scaledNumber = randomNumber * (this.max - this.min) + this.min;
var truncatedNumber = Math.trunc(scaledNumber);
next(_historical: Object[]): Object {

Check warning on line 17 in src/lib/mock-observations/helpers/RandIntGenerator.ts

View workflow job for this annotation

GitHub Actions / build

'_historical' is defined but never used
const randomNumber = Math.random();
const scaledNumber = randomNumber * (this.max - this.min) + this.min;
const truncatedNumber = Math.trunc(scaledNumber);
const retObject = {
[this.fieldToPopulate]: truncatedNumber
};
return retObject;
}

// TODO PB: extract to a utils class?
private validateName(name: string | null): string {
if (name === null || name.trim() === '') {
// TODO PB - custom / more specific error?
throw new Error('name is empty or null');
}
return name;
[this.fieldToPopulate]: truncatedNumber,
};
return retObject;
}

// TODO PB: extract to a utils class?
private validateConfig(config: { [key: string]: any }): void {
if (!config.hasOwnProperty(RandIntGenerator.MIN)) {
// TODO PB - custom / more specific error?
throw new Error('config is missing ' + RandIntGenerator.MIN);
}
if (!config.hasOwnProperty(RandIntGenerator.MAX)) {
// TODO PB - custom / more specific error?
throw new Error('config is missing ' + RandIntGenerator.MAX);
}
}
// TODO PB: extract to a utils class?
private validateName(name: string | null): string {
if (name === null || name.trim() === '') {
// TODO PB - custom / more specific error?
throw new Error('name is empty or null');
}
return name;
}

// TODO PB: extract to a utils class?
private validateConfig(config: {[key: string]: any}): void {
if (!Object.prototype.hasOwnProperty.call(config, RandIntGenerator.MIN)) {
// TODO PB - custom / more specific error?
throw new Error('config is missing ' + RandIntGenerator.MIN);
}
if (!Object.prototype.hasOwnProperty.call(config, RandIntGenerator.MAX)) {
// TODO PB - custom / more specific error?
throw new Error('config is missing ' + RandIntGenerator.MAX);
}
}
}

export default RandIntGenerator;
124 changes: 66 additions & 58 deletions src/lib/mock-observations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@ import {ERRORS} from '../../util/errors';
import {buildErrorMessage} from '../../util/helpers';

import {ModelParams} from '../../types/common';
import { ModelPluginInterface } from '../../interfaces';
import {ModelPluginInterface} from '../../interfaces';
import * as dayjs from 'dayjs';

import CommonGenerator from './helpers/CommonGenerator';
import RandIntGenerator from './helpers/RandIntGenerator';
import Generator from './interfaces/index';

const { InputValidationError } = ERRORS;
import Generator from './interfaces/index';
const {InputValidationError} = ERRORS;

export class MockObservations implements ModelPluginInterface {
// TODO PB - private members ?
staticParams: object | undefined;
errorBuilder = buildErrorMessage(MockObservations);
timestampFrom: dayjs.Dayjs | undefined;
timestampTo: dayjs.Dayjs | undefined;
duration: number = 0;
duration = 0;
timeBuckets: dayjs.Dayjs[] = [];
components: Record<string, Record<string, string>> = {}
components: Record<string, Record<string, string>> = {};
// components: object[] = [];
generatorConfigs: object = {};
dateList: dayjs.Dayjs[] = [];
Expand All @@ -30,33 +29,33 @@ export class MockObservations implements ModelPluginInterface {
console.log(inputs);
// TODO PB - consider making generators a member and creating them at config()
const generators = this.createGenerators(this.generatorConfigs);
let observations: ModelParams[] = [];
const observations: ModelParams[] = [];
for (const componentKey in this.components) {
if (this.components.hasOwnProperty(componentKey)) {
if (Object.prototype.hasOwnProperty.call(this.components, componentKey)) {
const component = this.components[componentKey];
for (const timeBucket of this.timeBuckets) {
let observation: ModelParams = {
const observation: ModelParams = {
timestamp: timeBucket.format('YYYY-MM-DD HH:mm:ss'),
// TODO PB -- this is not always true, the last timebucket might be shorter than the global duration. so duratio should be a property of timebucket (define a DTO for this)
duration: this.duration
duration: this.duration,
};
// TODO PB -- consider this way to copy key-value pairs from component to observation, it looks like an overkill
for (const key in component) {
if (Object.prototype.hasOwnProperty.call(component, key)) {
observation[key] = component[key];
}
for (const key in component) {
if (Object.prototype.hasOwnProperty.call(component, key)) {
observation[key] = component[key];
}
}
for (const generator of generators) {
// TODO PB - for future proofing, need to collecat historically generated data and pass it here
const generated: Record<string, any> = generator.next([]);
// TODO PB -- consider this way to copy key-value pairs from component to observation, it looks like an overkill
for (const key in generated) {
if (Object.prototype.hasOwnProperty.call(generated, key)) {
observation[key] = generated[key];
}
}
for (const key in generated) {
if (Object.prototype.hasOwnProperty.call(generated, key)) {
observation[key] = generated[key];
}
}
}
observations.push(observation);
observations.push(observation);
}
}
}
Expand All @@ -69,86 +68,95 @@ export class MockObservations implements ModelPluginInterface {
): Promise<ModelPluginInterface> {
if (staticParams === undefined) {
throw new InputValidationError(
this.errorBuilder({ message: 'Input data is missing' })
this.errorBuilder({message: 'Input data is missing'})
);
}
if ('timestamp-from' in staticParams) {
this.timestampFrom = dayjs(staticParams['timestamp-from'] as string);
}
else {
} else {
throw new InputValidationError(
this.errorBuilder({ message: 'timestamp-from missing from input data' })
);
this.errorBuilder({message: 'timestamp-from missing from input data'})
);
}
if ('timestamp-to' in staticParams) {
this.timestampTo = dayjs(staticParams['timestamp-to'] as string);
}
else {
} else {
throw new InputValidationError(
this.errorBuilder({ message: 'timestamp-to missing from input data' })
);
this.errorBuilder({message: 'timestamp-to missing from input data'})
);
}
if ('duration' in staticParams) {
this.duration = staticParams['duration'] as number;
}
else {
} else {
throw new InputValidationError(
this.errorBuilder({ message: 'duration missing from input data' })
);
this.errorBuilder({message: 'duration missing from input data'})
);
}
this.timeBuckets = this.createTimeBuckets(this.timestampFrom, this.timestampTo, this.duration);
this.timeBuckets = this.createTimeBuckets(
this.timestampFrom,
this.timestampTo,
this.duration
);

if ('components' in staticParams) {
// TODO PB -- is this casting needed?
this.components = staticParams['components'] as Record<string, Record<string, string>>;
}
else {
this.components = staticParams['components'] as Record<
string,
Record<string, string>
>;
} else {
throw new InputValidationError(
this.errorBuilder({ message: 'components missing from input data' })
);
this.errorBuilder({message: 'components missing from input data'})
);
}
if ('generators' in staticParams) {
// TODO PB -- is this casting needed?
this.generatorConfigs = staticParams['generators'] as object;
}
else {
} else {
throw new InputValidationError(
this.errorBuilder({ message: 'generators missing from input data' })
);
this.errorBuilder({message: 'generators missing from input data'})
);
}
// TODO PB -- remove dummy line
this.staticParams = staticParams;
return this;
// TODO PB -- remove dummy line
this.staticParams = staticParams;
return this;
}

private createTimeBuckets(timestampFrom: dayjs.Dayjs, timestampTo: dayjs.Dayjs, duration: number): dayjs.Dayjs[] {
let timeBuckets: dayjs.Dayjs[] = []
private createTimeBuckets(
timestampFrom: dayjs.Dayjs,
timestampTo: dayjs.Dayjs,
duration: number
): dayjs.Dayjs[] {
const timeBuckets: dayjs.Dayjs[] = [];
let currTimestamp: dayjs.Dayjs = timestampFrom;
while (currTimestamp.isBefore(timestampTo) || currTimestamp.isSame(timestampTo, 'second')) {
while (
currTimestamp.isBefore(timestampTo) ||
currTimestamp.isSame(timestampTo, 'second')
) {
timeBuckets.push(currTimestamp);
currTimestamp = currTimestamp.add(duration, 'second');
}
return timeBuckets;
}
return timeBuckets;
}

private createGenerators(generatorsConfig: object): Generator[] {
let generators: Generator[] = [];
Object.entries(generatorsConfig).forEach(([key, value]) => {
//console.log(`generator name: ${key}, generator config: ${value}`);
const generators: Generator[] = [];
Object.entries(generatorsConfig).forEach(([key, value]) => {
//console.log(`generator name: ${key}, generator config: ${value}`);
if ('common' === key) {
const commonGenerator = new CommonGenerator();
commonGenerator.initialise('common-generator', value);
generators.push(commonGenerator);
}
if ('randint' === key) {
for (const fieldToPopulate in value) {
const randIntGenerator = new RandIntGenerator()
const randIntGenerator = new RandIntGenerator();
randIntGenerator.initialise(fieldToPopulate, value[fieldToPopulate]);
generators.push(randIntGenerator)
generators.push(randIntGenerator);
}
}
}
});
return generators;
return generators;
}
}

Expand Down
16 changes: 8 additions & 8 deletions src/lib/mock-observations/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export interface Generator {
/**
* initialise the generator with the given name and config.
*/
initialise(name: String, config:{ [key: string]: any }): void
/**
* generate the next value, optionally based on historical values
*/
next(historical: Object[]): Object;
/**
* initialise the generator with the given name and config.
*/
initialise(name: String, config: {[key: string]: any}): void;
/**
* generate the next value, optionally based on historical values
*/
next(historical: Object[]): Object;
}
export default Generator;

0 comments on commit b1d8cc7

Please sign in to comment.