mirror of
https://github.com/eliasstepanik/strudel-docker.git
synced 2026-01-12 06:08:34 +00:00
began value api
This commit is contained in:
parent
c0bd0966a8
commit
4b124e3493
18
test/value.test.mjs
Normal file
18
test/value.test.mjs
Normal file
@ -0,0 +1,18 @@
|
||||
import { strict as assert } from 'assert';
|
||||
import { map, valued, mul } from '../value.mjs';
|
||||
|
||||
describe('Value', () => {
|
||||
it('unionWith', () => {
|
||||
const { value } = valued({ freq: 2000, distortion: 1.2 }).unionWith({ distortion: 2 }, mul);
|
||||
assert.deepStrictEqual(value, { freq: 2000, distortion: 2.4 });
|
||||
});
|
||||
|
||||
it('experiments', () => {
|
||||
assert.equal(map(mul(5), valued(3)).value, 15);
|
||||
assert.equal(map(mul(null), valued(3)).value, 0);
|
||||
assert.equal(map(mul(3), valued(null)).value, null);
|
||||
assert.equal(valued(3).map(mul).ap(3).value, 9);
|
||||
assert.equal(valued(mul).ap(3).ap(3).value, 9);
|
||||
assert.equal(valued(3).mul(3).value, 9);
|
||||
});
|
||||
});
|
||||
52
value.mjs
Normal file
52
value.mjs
Normal file
@ -0,0 +1,52 @@
|
||||
import { curry } from 'ramda';
|
||||
|
||||
function unionWithObj(a, b, func) {
|
||||
const common = Object.keys(a).filter((k) => Object.keys(b).includes(k));
|
||||
return Object.assign({}, a, b, Object.fromEntries(common.map((k) => [k, func(a[k], b[k])])));
|
||||
}
|
||||
|
||||
export const mul = curry((a, b) => a * b);
|
||||
|
||||
export const valued = (value) => {
|
||||
if (value?.constructor?.name === 'Value') {
|
||||
return value;
|
||||
}
|
||||
return Value.of(value);
|
||||
};
|
||||
|
||||
export class Value {
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
}
|
||||
static of(x) {
|
||||
return new Value(x);
|
||||
}
|
||||
get isNothing() {
|
||||
return this.value === null || this.value === undefined;
|
||||
}
|
||||
map(f) {
|
||||
if (this.isNothing) {
|
||||
return this;
|
||||
}
|
||||
return Value.of(f(this.value));
|
||||
}
|
||||
mul(n) {
|
||||
return this.map(mul).ap(n);
|
||||
}
|
||||
ap(other) {
|
||||
return valued(other).map(this.value);
|
||||
}
|
||||
unionWith(other, func) {
|
||||
const type = typeof this.value;
|
||||
other = valued(other);
|
||||
if (type !== typeof other.value) {
|
||||
throw new Error('unionWith: both Values must have same type!');
|
||||
}
|
||||
if (Array.isArray(type) || type !== 'object') {
|
||||
throw new Error('unionWith: expected objects');
|
||||
}
|
||||
return this.map((v) => unionWithObj(v, other.value, func));
|
||||
}
|
||||
}
|
||||
|
||||
export const map = curry((f, anyFunctor) => anyFunctor.map(f));
|
||||
Loading…
x
Reference in New Issue
Block a user