What does card_id => () => submitData(param_name, param_addr) do - node.js

Iam going through one of nodejs app and can find a syntax where code is:
const deleteData = async (
param_name,
param_addr
) => {
await callRequests(post_no, card_id => () => submitData(param_name, param_addr)
);
}
Iam not pretty sure what the double '=>' means here- " => () => " in the last line. Is it kind of double arrow function?

It's an lambda (arrow function) that returns a lambda.
A concrete example:
const sortFactory = (sign) => (a, b) => (a - b) * sign
const arr = [1, 3, 4, 2]
arr.sort(sortFactory(1)) // ascending
arr.sort(sortFactory(-1)) // ascending
In this question, it's a lambda with argument card_id that returns a no-argument lambda () => submitData(param_name, param_addr)

Related

Dynamic test data for test.each Jest

Is it possible to assign values at runtime for below Jest test.each example:
describe('jb-tests', () => {
jest.setTimeout(700000);
let table: Array<number[][]> = [[]];
beforeAll(() => {
//Below lines are just hardcoded values
table = [];
let test = [[1,2,3],[4,5,6],[7,8,9]]
table.push(test);
});
test.each(table)('.add(%i, %i)', (a, b, expected) => {
console.log("inside");
});
});
This test case is stuck and not showing any output. If I remove the jest.setTimeout then it fails with message "Exceeded timeout of 5000 ms for a test."
Building on the comment from #jonrsharpe, you can however specify values in the test.each() call.
describe('jb-tests', () => {
jest.setTimeout(700000);
test.each([
[1,2,3],
[4,5,6],
[7,8,9],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(Expected);
});
});
However, if you really need data from an external source, and want to process it, you can load it in the test code, or a beforeAll(). Note that the beforeAll() is evaluated at the very start, so what is loaded there is done at the start of processing the file, not as each test is run.
import * as NodeJSFS from 'fs/promises';
describe('jb-tests', () => {
jest.setTimeout(700000);
let table: Array<number[][]> = [[]];
beforeAll(async () => {
const FileContent$: Buffer = await NodeJSFSPromises.readFile('testdata.txt');
// Loop through FileContent$ (map, etc.) and load your table (table.push)
...
});
describe('adding addition describe for this section', () => {
for (const data of table) {
... // Parse data (one element of table)
it(`should add ${a} + ${b} to be ${Expected}', () => {
expect(a + b).toBe(Expected);
});
}
});
Just found an alternate solution: Populate the test data dynamically and then use describe block to execute test cases using test.each.
let test_data: Array<number[]> = [];
for(let i=0;i<3;i++){
test_data.push([i+0,i+1,i+2]);
}
describe('jb-tests', () => {
test.each(test_data)('.add(%i, %i, %i)', (a, b, c) => {
expect(a + b + c).toBeGreaterThan(0);
});
});

node js normal callback scenario for blocking code

I am getting into callbacks(do not want to use promise and async-await right now) and wrote code in node.js to sum a, b and c where I have created three functions for getting values of a, b and c.
// getting value of a
const getA = () => 10
// getting for value b
const getB = () => 20
// This function has to wait for 2 seconds to
const getC = (callback) => {
setTimeout(() => {
callback(30)
}, 2000);
}
const sum = (a, b, c, callback) => {
callback(a + b + c)
}
sum(getA(), getB(), getC((c) => c), (sum) => console.log(sum))
I want output 60 after waiting for getC() to finish execution, but didn't get any
I really suggest to use promises. I know there are some corner cases, where you can't. Why? Because we used to think in a way that the code is linear, and it is easier to the brain to process.
But for your question I would give a solution.
// getting value of a
const getA = () => 10;
// getting for value b
const getB = () => 20;
// This function has to wait for 2 seconds to
const getC = (callback) => {
setTimeout(() => {
callback(30);
}, 2000);
};
getC((val) => console.log(getA() + getB() + val));
So you wait until getC has finished, and use the callback to consume the c result.

How to delay event emission with rxpy/rxjs?

I've got two event streams. One is from an inductance loop, the other is an IP camera. Cars will drive over the loop and then hit the camera. I want to combine them if the events are within N milliseconds of each other (car will always hit the loop first), but I also want the unmatched events from each stream (either hardware can fail) all merged into a single stream. Something like this:
---> (only unmatched a's, None)
/ \
stream_a (loop) \
\ \
--> (a, b) ---------------------------> (Maybe a, Maybe b)
/ /
stream_b (camera) /
\ /
--> (None, only unmatched b's)
Now certainly I can hack my way around by doing the good ole Subject anti-pattern:
unmatched_a = Subject()
def noop():
pass
pending_as = [[]]
def handle_unmatched(a):
if a in pending_as[0]:
pending_as[0].remove(a)
print("unmatched a!")
unmatched_a.on_next((a, None))
def handle_a(a):
pending_as[0].append(a)
t = threading.Timer(some_timeout, handle_unmatched)
t.start()
return a
def handle_b(b):
if len(pending_as[0]):
a = pending_as[0].pop(0)
return (a, b)
else:
print("unmatched b!")
return (None, b)
stream_a.map(handle_a).subscribe(noop)
stream_b.map(handle_b).merge(unmatched_a).subscribe(print)
Not only is this rather hacky, but although I've not observed it I'm pretty sure there's a race condition when I check the pending queue using threading.Timer. Given the plethora of rx operators, I'm pretty sure some combination of them will let you do this without using Subject, but I can't figure it out. How does one accomplish this?
Edit
Although for organizational and operational reasons I'd prefer to stick to Python, I'll take a JavaScript rxjs answer and either port it or even possibly rewrite the entire script in node.
You should be able to solve the problem using auditTime and buffer. Like this:
function matchWithinTime(a$, b$, N) {
const merged$ = Rx.Observable.merge(a$, b$);
// Use auditTime to compose a closing notifier for the buffer.
const audited$ = merged$.auditTime(N);
// Buffer emissions within an audit and filter out empty buffers.
return merged$
.buffer(audited$)
.filter(x => x.length > 0);
}
const a$ = new Rx.Subject();
const b$ = new Rx.Subject();
matchWithinTime(a$, b$, 50).subscribe(x => console.log(JSON.stringify(x)));
setTimeout(() => a$.next("a"), 0);
setTimeout(() => b$.next("b"), 0);
setTimeout(() => a$.next("a"), 100);
setTimeout(() => b$.next("b"), 125);
setTimeout(() => a$.next("a"), 200);
setTimeout(() => b$.next("b"), 275);
setTimeout(() => a$.next("a"), 400);
setTimeout(() => b$.next("b"), 425);
setTimeout(() => a$.next("a"), 500);
setTimeout(() => b$.next("b"), 575);
setTimeout(() => b$.next("b"), 700);
setTimeout(() => b$.next("a"), 800);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs#5/bundles/Rx.min.js"></script>
If it's possible for b values to be closely followed by a values and you do not want them to be matched, you could use a more specific audit, like this:
const audited$ = merged$.audit(x => x === "a" ?
// If an `a` was received, audit upcoming values for `N` milliseconds.
Rx.Observable.timer(N) :
// If a `b` was received, don't audit the upcoming values.
Rx.Observable.of(0, Rx.Scheduler.asap)
);
I have developed a different strategy than Cartant, and clearly much less elegant, which may give you somehow a different result. I apologize if I have not understood the question and if my answer turns out to be useless.
My strategy is based on using switchMap on a$ and then bufferTime on b$.
This code emits at every timeInterval and it emits an object which contains the last a received and an array of bs representing the bs received during the time interval.
a$.pipe(
switchMap(a => {
return b$.pipe(
bufferTime(timeInterval),
mergeMap(arrayOfB => of({a, arrayOfB})),
)
})
)
If arrayOfB is empty, than it means that the last a in unmatched.
If arrayOfB has just one element, than it means that the last a has been matched by the b of the array.
If arrayOfB has more than one element, than it means that the last a has been matched by the first b of the array while all other bs are unmatched.
Now it is a matter of avoiding the emission of the same a more than
once and this is where the code gets a bit messy.
In summary, the code could look like the following
const a$ = new Subject();
const b$ = new Subject();
setTimeout(() => a$.next("a1"), 0);
setTimeout(() => b$.next("b1"), 0);
setTimeout(() => a$.next("a2"), 100);
setTimeout(() => b$.next("b2"), 125);
setTimeout(() => a$.next("a3"), 200);
setTimeout(() => b$.next("b3"), 275);
setTimeout(() => a$.next("a4"), 400);
setTimeout(() => b$.next("b4"), 425);
setTimeout(() => b$.next("b4.1"), 435);
setTimeout(() => a$.next("a5"), 500);
setTimeout(() => b$.next("b5"), 575);
setTimeout(() => b$.next("b6"), 700);
setTimeout(() => b$.next("b6.1"), 701);
setTimeout(() => b$.next("b6.2"), 702);
setTimeout(() => a$.next("a6"), 800);
setTimeout(() => a$.complete(), 1000);
setTimeout(() => b$.complete(), 1000);
let currentA;
a$.pipe(
switchMap(a => {
currentA = a;
return b$.pipe(
bufferTime(50),
mergeMap(arrayOfB => {
let aVal = currentA ? currentA : null;
if (arrayOfB.length === 0) {
const ret = of({a: aVal, b: null})
currentA = null;
return ret;
}
if (arrayOfB.length === 1) {
const ret = of({a: aVal, b: arrayOfB[0]})
currentA = null;
return ret;
}
const ret = from(arrayOfB)
.pipe(
map((b, _indexB) => {
aVal = _indexB > 0 ? null : aVal;
return {a: aVal, b}
})
)
currentA = null;
return ret;
}),
filter(data => data.a !== null || data.b !== null)
)
})
)
.subscribe(console.log);

How to mock curry function with Jest?

add.js
export default a => b => a+b;
module.js
import add from './add';
export default {
add1: n => add(1)(n),
};
test/module.js
import add from '../add';
import module from '../module';
jest.mock('../add', () => () => jest.fn());
module.add1(6);
expect(add.mock.calls).toHaveLength(1);
this can be called, but add wouldn't be a mock function, instead add() is a mock function, but the call params were not recorded correctly.
jest.mock('../add', () => () => jest.fn(a => b => a+b));
has also tried this, which doesn't seem to work correctly as well.
jest.mock('../add', jest.fn(a => b => a+b));
this would throw the inline function error
Is there a correct way to mock curry function at the moment?
Simple version should look like this
jest.mock('../add', () => (a) => jest.fn(b => a+b));
So you mock add module with a function that return that when gets called it returns the spy, problem you can't test anything on the spy.
So we need to refactor it so you have the add1 think as a spy in scope of the test
import add from '../add'
jest.mock('../add', () => jest.fn)
const addC = jest.fn()
add.mockImplemetation((a) => {
addC.mockImplementation((b => a+b)
return addC
})
I know this is a bit old but with the following answer I would have saved so much time...
import module from "./module";
const mockOperation = {
add: jest.fn()
};
jest.mock("./add", () => () => {
return mockOperation.add;
});
describe("add ", () => {
it("is called at least once", () => {
module.add1(6);
expect(mockOperation.add.mock.calls).toHaveLength(1);
});
});
A very importante thing: the constant function that you want to mock must start with the word mock. Otherwise it will throw an error.
const mockOperation = {
add: jest.fn()
};
With the mockOperation constant assigned to the add file, by reference is calling to it's add method which is a jest.fn()
I've had to do this a lot recently so I wrote a helper function to help me out.
curryMock = (baseFn, maxCurries) => {
var callIndex = 0
var curries = []
let returnFn
baseFn.mockImplementation((arg) => {
curries[callIndex] = 0
const fn = returnFn(callIndex)
callIndex++
return fn
})
returnFn = (index: number) => {
if (curries[index] < maxCurries) {
curries[index]++
return (arg: any) => {
baseFn.mock.calls[index].push(arg)
return returnFn(index)
}
}
}
}
You pass the function a jest.fn() and curryMock modifies it's implementation so that all the arguments return functions are called with will be added to the original jest.fn().mock.calls array. The second argument specifies how many times to return a function. maxCurries = 0 is for a regular function () => {},
maxCurries = 1is for a regular function() => => {}`, etc.
In your case:
import add from '../add';
import module from '../module';
jest.mock('../add');
curryMock(add)
module.add1(6);
expect(add).toHaveBeenCalledWith(1, 6);
//equivalent to
//expect(add).toHaveBeenNthCalledWith(1, 1, 6);
//if you others to test..
module.add7(4)
expect(add).toHaveBeenNthCalledWith(2, 7, 4)
curryMock is a quick utility function that I wrote for personal use. I will likely clean it up and extend it later, but I hope you get the idea: testing curried functions does not have to laborious.

Is there a way to write a Maybe.map with a promise inside?

I am following the first half of this excellent article, but there is a place I am stuck. https://jrsinclair.com/articles/2016/marvellously-mysterious-javascript-maybe-monad/
I have implemented a very similar Maybe monad, but one of my functions I need to pass to map is asynchronous. Ideally, I would be able to do this in a combination of .then() and map(). I want to do something like this...
const getToken = async (p) => {
let result = utils.Maybe.of(await makeAICCCall(p.aiccsid, p.aiccurl))
.map(parseAuthenticatedUser)
.thenMap(syncUserWithCore) <-- I can't figure this out
.map(managejwt.maketoken)
.value
return result;
}
I have tried everything I can think of, but I have not been able to figure this out.
natural transformations
Nesting of data containers can get messy, but there's a well-known technique for keeping them flat – eitherToPromise below is considered a natural transformation – it converts an Either to a Promise which allows it to be flattened in the .then chain, but also simultaneously prevents your value/error wires from getting crossed
Note: You probably want to use makeAICCall to return an Either (Left, Right) instead of Maybe because you'll be able to return an error message (instead of Nothing, which is less informative)
import { Left, Right, eitherToPromise } from './Either'
const makeAICCall = (...) =>
someCondition
? Left (Error ('error happened'))
: Right (someResult)
const getToken = p =>
makeAICCall (p.aiccsic, p.aiccurl) // => Promise<Either<x>>
.then (eitherToPromise) // => Promise<Promise<x>>
// => auto-flattened to Promise<x>
.then (syncUserWithCore) // => Promise<x>
.then (managejwt.maketoken) // => Promise<x>
Supply your favourite implementation of Either
// Either.js
export const Left = x =>
({
fold: (f,_) => f (x),
// map: f => Left (x),
// chain: ...,
// ...
})
export const Right = x =>
({
fold: (_,f) => f (x),
// map: f => Right (f (x)),
// chain: ...,
// ...
})
export const eitherToPromise = m =>
m.fold (x => Promise.reject (x), x => Promise.resolve (x))
runnable demo
const someAsyncCall = x =>
new Promise (r => setTimeout (r, 1000, x))
const authenticate = ({user, password}) =>
password !== 'password1'
? Left (Error ('invalid password'))
: Right ({user, id: 123})
const someSyncCall = token =>
Object.assign (token, { now: Date.now () })
const getToken = x =>
someAsyncCall (x)
.then (authenticate)
.then (eitherToPromise)
.then (someSyncCall)
// minimal dependencies
const Left = x =>
({ fold: (f,_) => f (x) })
const Right = x =>
({ fold: (_,f) => f (x) })
const eitherToPromise = m =>
m.fold (x => Promise.reject (x), x => Promise.resolve (x))
// test it
getToken ({user: 'alice', password: 'password1'})
.then (console.log, console.error)
// 1 second later ...
// { user: 'alice', id: 123, now: 1509034652179 }
getToken ({user: 'bob', password: 'password2'})
.then (console.log, console.error)
// 1 second later ...
// Error: invalid password ...
hey, lookit that
Our solution above results in a sequence of .then calls – an answer to your previous question demonstrates how such a program can be expressed in a different way
nullables
You should try your best to write functions that have a well-defined domain and codomain – you should be able to say, for example,
My function takes a string (domain) and returns a number (codomain) – anonymous wiseman
And avoid writing functions that have descriptions like,
It can take a number or a string and it returns an array, but could also return undefined. Oh and sometimes it can throw an error. But that's it, I'm pretty sure. – anonymous ignoramus
But of course we'll be dealing with null and undefined sometimes. How can we deal with it in a "functional way" – that's what you're wondering, right?
If you find yourself in an encounter with a function's nullable codomain (ie, can return a nullable), we can create a little helper to coerce it into a type we want. We'll demonstrate again with Either, just to tie it into the original code later
const Left = x =>
({ fold: (f,_) => f (x) })
const Right = x =>
({ fold: (_,f) => f (x) })
const eitherFromNullable = (x, otherwise = x) =>
x === null ||
x === undefined
? Left (otherwise)
: Right (x)
// !! nullable codomain !!
const find = (f, xs) =>
xs.find (x => f (x))
// example data
const data =
[1,2,3,4,5]
// perform safe lookups by wrapping unsafe find in eitherFromNullable
eitherFromNullable (find (x => x > 3, data))
.fold (console.error, console.log)
// <console.log> 4
eitherFromNullable (find (x => x > 5, data))
.fold (console.error, console.log)
// <console.error> undefined
eitherFromNullable (find (x => x > 5, data), Error (`couldn't find a big number !`))
.fold (console.error, console.log)
// <console.error> Error: couldn't find a big number !
nullables and natural transformations
Remember, we do our best to avoid nullables, but sometimes we can't help it. To show how this might tie in with the original code, let's pretend that instead of returning an Either, makeAICCall will instead return some x or some null
We just screen it with eitherFromNullable – new code in bold
const getToken = p =>
makeAICCall (p.aiccsic, p.aiccurl) // =&gt Promise<x?> could be null !!
.then (x => // =&gt Promise<Either<x>>
eitherFromNullable (x, Error ('bad aic call')))
.then (eitherToPromise) // =&gt Promise<Promise<x>>
// =&gt auto-flattened to Promise<x>
.then (syncUserWithCore) // =&gt Promise<x>
.then (managejwt.maketoken) // =&gt Promise<x>
stop hating lambdas
You probably wanna ditch that lambda, right ? Ok fine, just don't make it into a fetish.
const eitherFromNullable = otherwise => x =>
x == null ? Left (otherwise) : Right (x)
// ooooh, yeah, you like that
makeAICCall (p.aiccsic, p.aiccurl)
.then (eitherFromNullable (Error ('bad aic call')))
.then (eitherToPromise)
.then ...
don't get stuck
Nullable doesn't mean anything – you decide what it means in the context of your program.
const eitherFromNullable = (x, otherwise = x) =>
// we consider null and undefined nullable,
// everything else is non-null
x === null ||
x === undefined
? Left (otherwise)
: Right (x)
You could decide that false and 0 and empty string '' are also "nullable" – Or, you could just as easily decide to have very specific adapters eitherFromNull, eitherFromUndefined, eitherFromBoolean, etc – it's your program; it's up to you!
I feel like I'm starting to repeat myself ^_^'
make it routine
So you're saying you have lots of areas in your program where nulls are just unavoidable; maybe it's some dependency that you cannot get rid of. We'll imagine your code base with the following
// no one wants to do this for every endpoint!
const getUser = id =>
new Promise ((resolve, reject) =>
request ({url: '/users', id}, (err, res) =>
err
? reject (err)
: res.status === 403
? reject (Error ('unauthorized'))
res.body == null ?
? reject (Error ('not found'))
: resolve (User (JSON.parse (res.body)))))
It's using request which has an older Node-style callback interface that we're tired of wrapping in a promise
The API endpoints will respond with a 403 status if the requestor is unauthorized to view the requested resource
The API endpoints we talk to sometimes respond with null with status 200 (instead of 404) for missing resources; for example /users/999, where 999 is an unknown user id, will not trigger an error, but will fetch an empty response body
The API will respond with a valid JSON document for all other requests
We wish we could use something other than request, but our supervisor says No. We wish the API endpoints had different behavior, but that's out of our control. Still, it's within our power to write a good program
// functional programming is about functions
const safeRequest = (type, ...args) =>
new Promise ((resolve, reject) =>
request[type] (args, (err, res) =>
err
? reject (err)
: res.status === 403
? reject (Error ('unauthorized'))
res.body == null ?
? reject (Error ('not found'))
: resolve (JSON.parse (res.body))))
const getUser = id =>
safeRequest ('get', {url: '/users', id})
const createUser = fields =>
safeRequest ('post', {url: '/users', fields})
const updateUser = (id, fields) =>
safeRequest ('put', {url: '/users', id, fields})
Can it be improved more? Sure, but even if that's as far as you went, there's nothing wrong with that; all of the necessary checks happen for each endpoint because they were defined using safeRequest
Ok, so you wanna take it further? No problem. It's your program, do whatever you want!
const promisify = f => (...args) =>
new Promise ((resolve, reject) =>
f (...args, (err, x) =>
err ? reject (err) : resolve (x)))
const promiseFromResponseStatus = res =>
res.status === 403 // or handle other status codes here too !
? Promise.reject (Error ('unauthorized'))
: Promise.resolve (res)
const promiseFromNullableResponse = res =>
res.body == null // or res.body == '', etc
? Promise.reject (Error ('not found'))
: Promise.resolve (res.body)
const safeRequest = (type, ...args) =>
promisify (request [type]) (...args)
.then (promiseFromResponseStatus)
.then (promiseFromNullableResponse)
.then (JSON.parse)
const getUser = id =>
safeRequest ('get', {url: '/users', id})
const createUser ...
....

Resources