\$\begingroup\$
\$\endgroup\$
5
I'm working on a fluent interface builder that takes:
- an array of strings, each of which becomes a key to an object that is a function that follows the fluent interface pattern
- a terminator function which when called breaks the chain and does something else
I'm looking for some advice on how to improve this.
var Twitter = require('twit');
var secrets = require("./secrets/secrets");
var fs = require("fs");
var Twit = require('twit')
var T = new Twit({
consumer_key: secrets.consumer_key,
consumer_secret: secrets.consumer_secret,
access_token: secrets.access_token,
access_token_secret: secrets.access_token_secret,
timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
});
function fluentBuilder(options, terminator) {
let locals = options.reduce((opt, e) => {
opt[e] = null;
return opt;
}, {});
var methods = options.reduce((opt, e) => {
opt[e] = (val) => {
if (val) {
locals[e] = val;
return opt;
} else return locals[e];
}
return opt;
}, {});
methods.locals = locals;
methods["execute"] = terminator;
return methods;
}
var geocode = fluentBuilder(["lat", "long"],
function () {
var self = this;
return new Promise(resolve => {
T.get("geo/reverse_geocode", self.locals, function (err, data, results) {
resolve(data);
});
});
});
//calls to lat and long are stored on the self.locals variable which is passed to the Promise callback.
geocode.lat("34.0406")
.long("-84.2031")
.execute()
.then(data => {
console.log(data);
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
This seems like a lot of complexity for limited/no value. Could you not just pass an object literal like {lat: 34, long: 84}
to the geocoding function and be done with it, losing like 20 lines of code in the process?
A few other thoughts:
- Why are you requiring the same dependency twice under different names?
- Typically, javascript programmers like to use initial lowercase camel case. You have several variables named starting with capital letters which may not be desirable.
- You have inconsistent use of
let
vs.var
influentBuilder
. Why havelocals
defined withlet
andmethods
defined withvar
when both variables are used within the same scope and there is no "inner" code block to which you are trying to limit visibility oflocals
. Either one works exactly the same in this case, but it would be good to be consistent. - Your indentation is inconsistent.
- Why does
fluentBuilder
returnmethods
?
answered Aug 25, 2016 at 3:06
default
self.locals
and when the user calls execute all of the parameters that have been set via the calls (lat, long) are passed into the callback. \$\endgroup\$self.locals
variable of{lat: 34, long: 84}
. \$\endgroup\$