typescript-monads
Version:
Write cleaner TypeScript
74 lines • 2.58 kB
JavaScript
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { Maybe } from './maybe';
export function maybe(value) {
return new Maybe(value);
}
export function none() {
return Maybe.none();
}
export function some(value) {
return maybe(value);
}
/**
* Creates a function that returns a Maybe for the given property path.
*
* This is a powerful utility for safely navigating nested object structures.
* It creates a type-safe property accessor function that returns a Maybe
* containing the value at the specified path if it exists, or None if any
* part of the path is missing.
*
* @param path A dot-separated string path to the desired property
* @returns A function that takes an object and returns a Maybe of the property value
*
* @example
* const getEmail = maybeProps<User>('profile.contact.email');
*
* // Later in code
* const emailMaybe = getEmail(user);
* // Returns Some(email) if user.profile.contact.email exists
* // Returns None if any part of the path is undefined/null
*
* // Use with filter
* const validEmail = getEmail(user).filter(email => email.includes('@'));
*
* // Use with match
* getEmail(user).match({
* some: email => sendVerification(email),
* none: () => showEmailPrompt()
* });
*/
export function maybeProps(path) {
var segments = path.split('.');
return function (obj) {
var e_1, _a;
var current = obj;
try {
for (var segments_1 = __values(segments), segments_1_1 = segments_1.next(); !segments_1_1.done; segments_1_1 = segments_1.next()) {
var segment = segments_1_1.value;
if (current === null || current === undefined || !(segment in current)) {
return none();
}
current = current[segment];
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (segments_1_1 && !segments_1_1.done && (_a = segments_1.return)) _a.call(segments_1);
}
finally { if (e_1) throw e_1.error; }
}
return maybe(current);
};
}
//# sourceMappingURL=maybe.factory.js.map