Skip to content

Commit fe22df2

Browse files
committed
feat: 🎸 add converter promise factory to cps factory
1 parent e40e1c5 commit fe22df2

2 files changed

Lines changed: 28 additions & 8 deletions

File tree

index.js

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -331,19 +331,29 @@ const CPS = cpsFn => {
331331
/* ------- CPS utils ------ */
332332

333333
/**
334-
* Convert NodeJS Api function to CPS factory
334+
* Convert NodeJS function to CPS factory
335335
*
336-
* @param {Function} nodeApi - function with Node style callback `cb` as last argument:
337-
* cb(error, result)
338-
* @returns {Function} node2cps(nodeApi) - CPS factory function taking all args but last
339-
* that returns CPS function with 2 callbacks similar to Promise
336+
* @param {Function} nodeF - function with Node style callback `cb` as last argument:
337+
* cb(error, result)
338+
* @returns {Function} node2cps(nodeF) - CPS factory function taking all args but last
339+
* that returns CPS function with 2 callbacks similar to Promise
340340
*/
341-
const node2cps = nodeApi => (...args) => CPS(
342-
(onRes, onErr) => nodeApi(...args, (e, ...x) => e ? onErr(e) : onRes(...x))
341+
const node2cps = nodeF => (...args) => CPS(
342+
(onRes, onErr) => nodeF(...args, (e, ...x) => e ? onErr(e) : onRes(...x))
343343
)
344344

345+
/**
346+
* Convert Promise factory to CPS factory
347+
* makes promise lazy by defering promise creation
348+
*
349+
* @param {Function} promiseFactory - function that returns Promise
350+
* @returns {Function} promiseF2cps(promiseFactory) - CPS factory function
351+
*/
352+
const promiseF2cps = promiseFactory => (...args) => (onRes, onErr) => promiseFactory(...args).then(onRes, onErr)
353+
354+
345355
module.exports = {
346356
curry2, pipeline, pipe,
347357
of, ofN, map, chain, filter, scan, scanS, ap, lift2,
348-
CPS, node2cps
358+
CPS, node2cps, promiseF2cps
349359
}

test/promiseF2cps.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const test = require('./config')
2+
const { promiseF2cps } = require('..')
3+
4+
test('promiseF2cps converts fulfilled promise to cps factory returning value in the 1st callback', async t=>{
5+
await promiseF2cps(x=>Promise.resolve(x))(3)(t.cis(3))
6+
})
7+
8+
test('promiseF2cps converts rejected promise to cps factory returning value in the 2nd callback', async t=>{
9+
await promiseF2cps(x=>Promise.reject(x))(3)(null,t.cis(3))
10+
})

0 commit comments

Comments
 (0)