[JS Compse] 4. A collection of Either examples compared to imperative code
For if..else:
const showPage() { if(current_user) { return renderPage(current_user); } else { return showLogin(); } } const showPage() { fromNullable(current_user) .fold(showLogin, renderPage) }
const getPrefs = user => { if(user.premium) { return loadPrefs(user.preferences) } else { return defaultPrefs; } } const getPrefs = user => (user.premium ? Right(user): Left('not premium')) .map(p => user.preferences) .fold( x => defaultPrefs, x => loadPrefs(x) )
const streetName = user => { const address = user.address; if(address) { const street = address.street; if(street) { return street.name; } } return 'no street'; } cosnt streetName = user => fromNullable(user.address) .flatMap(address => fromNullable(address.street)) .map(street => street.name) .fold(e => 'no street', n => n)
const concatUniq = (x, ys) => { const found = ys.filter(y => y === x)[0] return found ? ys : ys.concat(x); } const concatUniq = (x, ys) => fromNullable(ys.filter(y => y === x)[0]) // fromNullable needs value .fold(() => ys.concat(x), y => ys)
const wrapExamples = example => { if(example.previewPath){ try { example.preview = fs.readFileSync(example.previewPath) } catch(e) { } return example; } } const readFile = x => tryCatch(() => readFileSync(x)); const wrapExample = example => fromNullabel(exampe.previewPath) .flatMap(readFile) .fold(() => example, ex => Object.assign({preview: p}, ex); )
const parseDbUrl = cfg => { try { const c = JSON.parse(cfg); if(c.url) { return c.url.match(/..../) } catch(e) { return null } } } const parseDbUrl = cfg => tryCatch(() => JSON.parse(cfg)) .flatMap(c => fromNullable(c.url)) .fold( e => null, u => u.match(/..../) )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-12-14 [AngularJS] Services, Factories, and Providers -- value & Providers
2015-12-14 [AngularJS] Services, Factories, and Providers -- Service vs Factory
2014-12-14 [MongoDB] Query, update, index and group