Files

41 lines
2.5 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const context = { window: {} };
vm.runInNewContext(fs.readFileSync('web/js/composite.js', 'utf8'), context);
const api = context.window.ExoComposite;
const index = { fields: [
{ name: 'ts', unit: 'K', shape: [3, 1, 2, 2], min: 200, max: 300 },
{ name: 'pr', unit: 'm s-1', shape: [3, 1, 2, 2], min: 0, max: 1e-6 },
{ name: 'sg', unit: 'm2 s-2', shape: [1, 1, 2, 2], min: -981, max: 981 }
] };
const descriptor = api.create(index, 9.81);
assert.ok(descriptor);
const mismatched = structuredClone(index);mismatched.fields[1].shape[2] = 3;
assert.equal(api.create(mismatched, 9.81), null);
const reversed = structuredClone(index);reversed.fields[1].max = -1;
assert.equal(api.create(reversed, 9.81), null);
assert.equal(api.create(index, Number.MIN_VALUE), null);
assert.deepEqual(Array.from(descriptor.channels, c => [c.channel, c.name]), [['red', 'ts'], ['green', 'pr'], ['blue', 'sg']]);
assert.equal(descriptor.channels[1].label, 'Precipitation');
assert.equal(descriptor.channels[1].unit, 'mm/day');
assert.equal(api.normalise(250, descriptor.channels[0]), 0.5);
assert.equal(api.normalise(0.5e-6, descriptor.channels[1]), 0.5);
assert.equal(api.normalise(0, descriptor.channels[2]), 0.5);
assert.equal(api.normalise(-10000, descriptor.channels[2]), 0);
assert.equal(api.normalise(1000, descriptor.channels[2]), 1);
assert.equal(api.normalise(NaN, descriptor.channels[0]), null);
assert.equal(api.create(index, 0), null);
assert.equal(api.create(index, Infinity), null);
assert.equal(api.create({ fields: index.fields.filter(field => field.name !== 'pr') }, 9.81), null);
assert.equal(api.create({ fields: index.fields.map(field => field.name === 'ts' ? { ...field, unit: 'm' } : field) }, 9.81), null);
assert.equal(api.create({ fields: index.fields.map(field => field.name === 'ts' ? { ...field, shape: [3, 2, 2, 2] } : field) }, 9.81), null);
const constant = { fields: index.fields.map(field => field.name === 'pr' ? { ...field, min: 0, max: 0 } : field) };
const constantDescriptor = api.create(constant, 9.81);
assert.equal(api.normalise(0, constantDescriptor.channels[1]), 0);
const constantNonzero = { fields: index.fields.map(field => field.name === 'pr' ? { ...field, min: 1e-6, max: 1e-6 } : field) };
assert.equal(api.normalise(1e-6, api.create(constantNonzero, 9.81).channels[1]), 0.5);
assert.equal(api.normalise(2e-6, descriptor.channels[1]), 1);
console.log('web-composite: ok');