Firman Jamal
Firman Jamal

Reputation: 123

How does the data parameter works with this function?

I wanted to modify this code into typescript because I don't know how to make a type definition file for this project (@types)

jsHue Repo

Here's the problem, I see there's a method for example (setLightState) where it takes in an ID and calls a network request.

But in the documentation, it also passes in another argument for HTTP Body request.

In documentation:

user.setLightState(3, { bri: 128 })

So I was wondering where does the second argument comes from in the js lib.

The function of setLightState(), from my understanding setLightState, takes in a method and id then returns the url function

setLightState: _parametrize(_put, id => `${_lightUrl(id)}/state`)

And the _parametrized function confused me a lot

var _parametrize = (method, url) => (p, ...rest) => method(url(p), ...rest);

Upvotes: 0

Views: 91

Answers (1)

Rocky Sims
Rocky Sims

Reputation: 3608

It's no surprise you are finding this confusing. This code is excessively abstracted and has poor variable names.

Let's try to make sense of setLightState by undoing some of the abstraction.
The following four lines of code all have the same result (just more hard coded):

setLightState: _parametrize(_put, id =>${_lightUrl(id)}/state)

setLightState: (p, ...rest) => _put(${_lightUrl(p)}/state, ...rest)

setLightState: (p, ...rest) => (_requestJson.bind(null, 'PUT'))(${_lightUrl(p)}/state, ...rest)

setLightState: (p, ...rest) => _requestJson('PUT',${_lightUrl(p)}/state, ...rest)

So when you call setLightState(3, { bri: 128 }), the { bri: 128 } goes to ...rest and ends up being the data parameter passed to the _requestJson function.

I hope that helps.

Upvotes: 1

Related Questions