UNPKG

@parischap/pretty-print

Version:
82 lines 2.54 kB
/** * This module implements a type that takes care of the formatting of primitive values, e.g. * surround strings in quotes, add 'n' at the end of a bigint, display numbers with a thousand * separator,... * * With the make function, you can define your own instances if the provided ones don't suit your * needs. */ import { MFunction, MInspectable, MMatch, MPipeable, MString, MTypes } from '@parischap/effect-lib'; import { Either, Equal, flow, Function, Hash, Number, pipe, Predicate, String, Struct } from 'effect'; import * as PPValue from './Value.js'; /** * Module tag * * @category Models */ export const moduleTag = '@parischap/pretty-print/PrimitiveFormatter/'; const _TypeId = /*#__PURE__*/Symbol.for(moduleTag); /** * Type guard * * @category Guards */ export const has = u => Predicate.hasProperty(u, _TypeId); /** * Equivalence * * @category Equivalences */ export const equivalence = (self, that) => that.id === self.id; /** Base */ const _TypeIdHash = /*#__PURE__*/Hash.hash(_TypeId); const base = { [_TypeId]: _TypeId, [Equal.symbol](that) { return has(that) && equivalence(this, that); }, [Hash.symbol]() { return pipe(this.id, Hash.hash, Hash.combine(_TypeIdHash), Hash.cached(this)); }, [MInspectable.IdSymbol]() { return this.id; }, ... /*#__PURE__*/MInspectable.BaseProto(moduleTag), ...MPipeable.BaseProto }; /** * Constructor * * @category Constructors */ export const make = ({ id, action }) => Object.assign(MFunction.clone(action), { id, ...base }); /** * Returns the `id` property of `self` * * @category Destructors */ export const id = /*#__PURE__*/Struct.get('id'); /** * PropertyFormatter contructor that builds an instance that works like util.inspect * * @category Constructors */ export const utilInspectLikeMaker = ({ id, maxStringLength, numberFormatter } = { id: 'UtilInspectLike', maxStringLength: 10000, numberFormatter: new Intl.NumberFormat() }) => make({ id, action: flow(PPValue.content, MMatch.make, MMatch.when(MTypes.isString, flow(Either.liftPredicate(flow(String.length, Number.greaterThan(maxStringLength)), Function.identity), Either.map(flow(String.takeLeft(maxStringLength), MString.append('...'))), Either.merge, MString.append("'"), MString.prepend("'"))), MMatch.when(MTypes.isNumber, flow(n => numberFormatter.format(n))), MMatch.when(MTypes.isBigInt, flow(n => numberFormatter.format(n), MString.append('n'))), MMatch.orElse(MString.fromPrimitive)) }); //# sourceMappingURL=PrimitiveFormatter.js.map