1/* 2value.mjs - <short description TODO> 3Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/value.mjs> 4This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. 5*/ 6 7import { curry } from './util.mjs'; 8import { logger } from './logger.mjs'; 9 10export function unionWithObj(a, b, func) { 11 if (b?.value !== undefined && Object.keys(b).length === 1) { 12 // https://codeberg.org/uzu/strudel/issues/1026 13 logger(`[warn]: Can't do arithmetic on control pattern.`); 14 return a; 15 } 16 const common = Object.keys(a).filter((k) => Object.keys(b).includes(k)); 17 return Object.assign({}, a, b, Object.fromEntries(common.map((k) => [k, func(a[k], b[k])]))); 18} 19 20export const mul = curry((a, b) => a * b); 21 22export const valued = (value) => { 23 if (value?.constructor?.name === 'Value') { 24 return value; 25 } 26 return Value.of(value); 27}; 28 29export class Value { 30 constructor(value) { 31 this.value = value; 32 } 33 static of(x) { 34 return new Value(x); 35 } 36 get isNothing() { 37 return this.value === null || this.value === undefined; 38 } 39 map(f) { 40 if (this.isNothing) { 41 return this; 42 } 43 return Value.of(f(this.value)); 44 } 45 mul(n) { 46 return this.map(mul).ap(n); 47 } 48 ap(other) { 49 return valued(other).map(this.value); 50 } 51 unionWith(other, func) { 52 const type = typeof this.value; 53 other = valued(other); 54 if (type !== typeof other.value) { 55 throw new Error('unionWith: both Values must have same type!'); 56 } 57 if (Array.isArray(type) || type !== 'object') { 58 throw new Error('unionWith: expected objects'); 59 } 60 return this.map((v) => unionWithObj(v, other.value, func)); 61 } 62} 63 64export const map = curry((f, anyFunctor) => anyFunctor.map(f));