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);
});
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\$