it("shall receive the8-zone rgbww/cw command on zone 1", function (done) { var test = function(total, commandName) { var innerCalls = [ commands.fullColor8Zone[commandName](1) ]; var innerTest = function(total, command) { expect(command).toBeDefined(); return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(light._lastBytesSent.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(light._lastBytesSent)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( ["nightMode", "whiteMode", "on", "off"], test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
Inquisitor.prototype._performArrayInquiry = function _performArrayInquiry(results, questions) { return bPromise.reduce(questions, this._reduceInquiries.bind(this), {}) .then(function(answers) { results[questions] = answers; return results; }); };
Job.prototype.getState = function() { var _this = this; var fns = [ { fn: 'isCompleted', state: 'completed' }, { fn: 'isFailed', state: 'failed' }, { fn: 'isDelayed', state: 'delayed' }, { fn: 'isActive', state: 'active' }, { fn: 'isWaiting', state: 'waiting' }, { fn: 'isPaused', state: 'paused' } ]; return Promise.reduce( fns, function(state, fn) { if (state) { return state; } return _this[fn.fn]().then(function(result) { return result ? fn.state : null; }); }, null ).then(function(result) { return result ? result : 'stuck'; }); };
return readdirAsync(dir).then(function (files) { files = files || []; return Promise.reduce(files, function (results, file) { var fpath = path.join(dir, file); return lstatAsync(fpath).then(function (result) { if (result.isDirectory()) { return readDir(fpath, options, depth + 1, messages); } else if (options.followSymlinks && result.isSymbolicLink()) { return readlinkAsync(fpath).then(function (linkPath) { linkPath = path.resolve(dir, linkPath); return lstatAsync(linkPath).then(function (result) { if (result.isFile()) { return linkPath; } return readDir(linkPath, options, depth + 1, messages); }); }); } else if (depth === 1 && file === 'package.json') { return parsePackageJson(fpath, messages); } else { return fpath; } }).then(function (result) { results[file] = result; return results; }); }, {}); });
const generateMainTree = rootGenre => { let subgenres = rootGenre.related('subgenres'); let promises = []; const addGenres = genres => { genres.each(genre => { let result = addGeneration(genre) genre.set('subgenres', result); promises.push(result) }) } let addGeneration = genre => { return genre.related('subgenres').fetch() .then(genres => { addGenres(genres); return genres; }) } addGenres(subgenres); promises.push(Promise.resolve('foo')); return Promise.reduce(promises, (results, next) => { return Promise.all(promises); }) .then(promises => rootGenre) }
TestList.prototype.getTestFiles = function (tokens) { tokens = tokens || [ ]; return Promise.reduce(this.getTestDirs(), function (obj, testDir) { return fs.readdir$(testDir) .catch(function (err) { if (err.code === 'ENOENT') { return [ ]; } throw err; }) .each(function (filename) { if (!/\.js$/.test(filename)) { return; } var split = filename.split('.').slice(0, -1); var keep = tokens.length === 0 || split.reduce(function (ret, cur) { return ret || tokens.indexOf(cur) > -1; }, false); if (!keep) { return; } obj[testDir] = obj[testDir] || [ ]; if (filename !== 'init.js') { obj[testDir].push(PATH.join(testDir, filename)); } }).return(obj); }, { }); };
Config.prototype.getFileSet = function(want, dontWant, callback) { var self = this; if (isa(want, String)) { want = [want]; // want is an Array } if (isa(dontWant, String)) { dontWant = [dontWant]; // dontWant is an Array } dontWant = dontWant.map(function(p) { return p ? self.resolvePath(p) : p; }); Bluebird.reduce(want, function(allThatIWant, patternEntry) { var pattern = isa(patternEntry, String) ? patternEntry : patternEntry.src; var attrs = patternEntry.attrs || []; var patternUrl = url.parse(pattern); if (patternUrl.protocol === 'file:') { pattern = patternUrl.hostname + patternUrl.path; } else if (patternUrl.protocol) { return allThatIWant.concat({src: pattern, attrs: attrs}); } return filesetAsync([self.resolvePath(pattern)], dontWant).then(function(files) { return allThatIWant.concat(files.map(function(f) { f = self.reverseResolvePath(f); return {src: f, attrs: attrs}; })); }); }, []).asCallback(callback); };
function listReachableServers(filter_locations) { var locations = config.eid.locations; var reachable_servers = []; var port = config.eid.port; return Promise.reduce(locations, function (previous, row) { return new Promise(function (resolve, reject) { var url = row.host + '/' + port + '/eid/orders/api.php' curl.request({ url: url, pretend: true }, function (err, stdout, meta) { if (err) { resolve(reachable_servers); } else { if (filter_locations && filter_locations.length > 0) { if (_.indexOf(filter_locations, row.name) > -1) reachable_servers.push(row); } else { reachable_servers.push(row); } resolve(reachable_servers); } }); }); }, 0); }
.then(function (reachable) { return Promise.reduce(reachable, function (previous, row) { return _getSynchronizedPatientLabResults(row, patientUuId) .then(function (obj) { results.data.push(obj); return new Promise(function (resolve, reject) { resolve(results); }) }) .catch(function (error) { //catch errors and continue results.errors.push(error); return new Promise(function (resolve, reject) { resolve(results); }) }); }, 0) .then(function (data) { return new Promise(function (resolve, reject) { resolve(results); }); }) });
async function getKibanaPayload({ app, request, includeUserProvidedConfig, injectedVarsOverrides }) { const uiSettings = server.uiSettings(); const translations = await uiI18n.getTranslationsForRequest(request); return { app: app, nav: uiExports.navLinks.inOrder, version: kbnServer.version, buildNum: config.get('pkg.buildNum'), buildSha: config.get('pkg.buildSha'), basePath: config.get('server.basePath'), serverName: config.get('server.name'), devMode: config.get('env.dev'), translations: translations, uiSettings: await props({ defaults: uiSettings.getDefaults(), user: includeUserProvidedConfig && uiSettings.getUserProvided(request) }), vars: await reduceAsync( uiExports.injectedVarsReplacers, async (acc, replacer) => await replacer(acc, request, server), defaults(injectedVarsOverrides, await app.getInjectedVars() || {}, uiExports.defaultInjectedVars) ), }; }
export function get (cluster, nodes, section) { const promise = Promise.reduce(Object.keys(nodes), (obj, node) => { const url = buildConfigUrl(node, nodes[node], section); return getConfig(node, url).then(({node, config}) => { obj[node] = config; return obj; }); }, {}); promise.then((nodeConfigs) => { const jsonOut = nmo.config.get('json'); if (jsonOut) { console.log(nodeConfigs); return nodeConfigs; } Object.keys(nodeConfigs).forEach(node => { var msg = [ 'NODE ' + node + ':', prettyjson.render(nodeConfigs[node], {}) ].join('\n'); console.log(msg); }); }); return promise; }
it("shall receive the rgbww/cw command", function (done) { var test = function(total, commandName) { var innerCalls = [ commands.fullColor[commandName](1) ]; var innerTest = function(total, command) { expect(command).toBeDefined(); return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(light._lastBytesSent.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(light._lastBytesSent)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( [/*"allOn", "allOff",*/ "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectSpeedUp", "effectSpeedDown", "link", "unlink" ], test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
it("shall receive the command rgbww/cw effectMode", function (done) { var calls = [ [1, 1], [1, 5], [1, 9] ]; var test = function(total, args) { var innerCalls = [ commands.fullColor.effectMode.apply(commands.fullColor, args) ]; var innerTest = function(total, command) { expect(command).toBeDefined(); return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(light._lastBytesSent.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(light._lastBytesSent)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( calls, test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
it("shall receive the bridge command", function (done) { var test = function(total, commandName) { var innerCalls = [ commands.bridge[commandName].call(commands.bridge) ]; var innerTest = function(total, command) { expect(command).toBeDefined(); return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(light._lastBytesSent.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(light._lastBytesSent)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( [ "on", "off", "nightMode", "whiteMode", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectModeNext", "effectSpeedUp", "effectSpeedDown" ], test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
it("shall receive the rgb command", function (done) { var test = function(total, commandName) { var innerCalls = [ commands.rgb[commandName](), commands2.rgb[commandName]() ]; var innerTest = function(total, command) { return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(command.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(command)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( ["on", "off", "speedUp", "speedDown", "effectSpeedUp", "effectSpeedDown", "brightUp", "brightDown"], test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
Collector.prototype.saveCollections = function saveCollections(collections, done) { if (!util.isArray(collections)) { throw new Error('collections parametor must be Array.'); } if (typeof done !== 'function' || !done) { throw new Error('done parametor must be Function.'); } const save = this.save.bind(this); const savedItems = []; Promise.reduce(collections, (total, item)=> { return new Promise((resolve, reject)=> { save(item, (err, savedItem)=> { if (err) { return reject(err); } if (savedItem) { savedItems.push(savedItem); } resolve(); }); }); }, null) .then(()=> { return done(null, savedItems); }) .catch((err)=> { return done(err); }); };
it("shall receive the command rgb hue", function (done) { var calls = [ [5], [50] ]; var test = function(total, args) { var innerCalls = [ commands.rgb.hue.apply(commands.rgb, args), commands2.rgb.hue.apply(commands.rgb, args) ]; var innerTest = function(total, command) { return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(command.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(command)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( calls, test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
Memcached.prototype._key = function (key) { var that = this; key = Utils.key([], key); return Promise.reduce(key.split('/'), function (path, key) { path.push(key); return that._get(path.join('/') + '_ns').then(function (count) { var commit = function (path, key, count) { path.pop(); path.push(key + count); return path; }; if (count === false) { count = Date.now(); return that._set(path.join('/') + '_ns', count, 0).then(function () { return commit(path, key, count); }); } else { return commit(path, key, count); } }); }, []).then(function (key) { return key.join('/'); }); };
Manager.prototype.setModel = function(model, properties) { var promises = []; properties = properties || {}; if (model.isNew() && properties && properties.id) { promises.push(function() { return this.fetch(model, { id: properties.id }).then(function(result) { return result; }); }.bind(this)); } else { promises.push(function() { return (model.isNew() || model.hasChanged()) ? model.save() : model; }); } Object.keys(properties).forEach(function(key) { var value = properties[key]; var relation = model[key] instanceof Function ? model[key].call(model) : null; var type = relation ? relation.relatedData.type : 'scalar'; var method = 'set' + type.charAt(0).toUpperCase() + type.slice(1); var setter = this[method].bind(this); promises.push(function(result) { return setter(result, key, value, relation).then(function() { return result; }); }); }.bind(this)); return Promise.reduce(promises, function(result, promise) { return promise(result); }, []); };
.map(Object.keys(votes), typeKey => { let voters = votes[typeKey]; return Promise.reduce(voters, (total, vote) => { let uid = vote.value; return total + (1 * uidMultipliers[uid]); }, 0) })
function _concatenate(files) { return Promise.reduce(files.map(function (file) { return fs.readFileAsync(file); }), function (result, rendered) { return result + "\n\n\n" + rendered; }, ""); }
exports.init = function () { if (process.env.REGISTER_TEMPLATES === 'false' || !templateConfig) { return; } return Promise.reduce(templateConfig, (agg, template) => { return co(function*() { let existing = yield TemplateDefinition.findOne({ key: template.key }), dataArrayChanges = existing && JSON.stringify(existing.availableData) !== JSON.stringify(template.availableData); if (!existing) { winston.debug(chalk.dim(`Creating template definition: ${template.key}`)); yield (new TemplateDefinition(template)).save(); winston.debug(chalk.dim(`Saved template definition: ${template.key}`)); } else if (existing && dataArrayChanges || paths.filter(p => existing[p] !== template[p]).length > 0) { winston.debug(chalk.dim(`Detected change in template definition: ${template.key}`)); _.assign(existing, template); yield existing.save(); winston.debug(chalk.dim(`Updated template definition: ${template.key}`)); } return agg; }); }, []); };
.then(genre => { let promises = [], artists = genre.related('founders'); const addArtists = (artists) => { artists.each(artist => { let result = addGeneration(artist) artist.set('proteges', result); promises.push(result); }) } let addGeneration = (artist) => { return artist.related('proteges').fetch() .then(artists => { addArtists(artists); return artists; }) } addArtists(artists); return Promise.reduce(promises, (results, next) => { return Promise.all(promises); }) .then(promises => genre) })
const listOf = (check, msg) => (list) => { const validator = extern(check, msg || MSG.LIST_ITEM_NOT_SPEC); const reducer = (result, item) => result ? result : validator(item); return Bluebird.reduce(list, reducer, null); };
invoke(commandsArray, allowEntryPoints) { const command = this.getCommand(commandsArray, allowEntryPoints); this.convertShortcutsIntoOptions(command); this.assignDefaultOptions(command); this.validateOptions(command); const events = this.getEvents(command); const hooks = this.getHooks(events); if (process.env.SLS_DEBUG) { this.serverless.cli.log(`Invoke ${_.join(commandsArray, ':')}`); if (hooks.length === 0) { const warningMessage = 'Warning: The command you entered did not catch on any hooks'; this.serverless.cli.log(warningMessage); } } return BbPromise.reduce(hooks, (__, hook) => hook.hook(), null) .catch(TerminateHookChain, () => { if (process.env.SLS_DEBUG) { this.serverless.cli.log(`Terminate ${_.join(commandsArray, ':')}`); } return BbPromise.resolve(); }); }
it("shall send a stacked command", function (done) { var calls = [ commands.rgbw.rgb255(255, 255, 255), commands2.rgbw.rgb255(255, 255, 255), commands.rgbw.rgb(255, 255, 255), commands2.rgbw.rgb(255, 255, 255) ]; var test = function(total, command) { return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(flattenDeep(command).length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(flattenDeep(command))); bytesReceived = []; total += bytesReceived.length }); }; Promise.reduce( calls, test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
return Promise.try(() => { if (values === undefined) { core.log('info', `${name} is not set in the config file`); return {}; } if (!Array.isArray(values)) { // eslint-disable-next-line no-param-reassign values = [values]; } // eslint-disable-next-line no-param-reassign values = _.map(values, (value) => { if (typeof value === 'string') { const path = pathLib.resolve(core.getAppRootDir(), value); core.log('info', `Loading ${name} from ${path}`); return fs .readFileAsync(path) .then(yaml.safeLoad); } else if (typeof value === 'object' && !Array.isArray(value)) { core.log('info', `Loading ${name} from the config file`); return value; } throw new Err('config.%s must be an object or filename,' + ' or an array of objects and/or filenames', name); }); return Promise.reduce(values, _.extend, {}); });
it("shall receive the white command on zone 1", function (done) { var test = function(total, commandName) { var innerCalls = [ commands.white[commandName](1), commands2.white[commandName](1) ]; var innerTest = function(total, command) { return light.sendCommands(command) .then(function () { expect(bytesReceived.length).toBe(command.length); expect(JSON.stringify(bytesReceived)).toEqual(JSON.stringify(command)); bytesReceived = []; total += bytesReceived.length }) }; return Promise.reduce( innerCalls, innerTest, 0 ) }; Promise.reduce( ["nightMode", "maxBright", "on", "off"], test, 0 ).catch(function (error) { console.log(error); expect(true).toBe(false) }).finally(function () { done(); }) });
function verify (cache, opts) { opts = VerifyOpts(opts) opts.log.silly('verify', 'verifying cache at', cache) return BB.reduce([ markStartTime, fixPerms, garbageCollect, rebuildIndex, cleanTmp, writeVerifile, markEndTime ], (stats, step, i) => { const label = step.name || `step #${i}` const start = new Date() return BB.resolve(step(cache, opts)).then(s => { s && Object.keys(s).forEach(k => { stats[k] = s[k] }) const end = new Date() if (!stats.runTime) { stats.runTime = {} } stats.runTime[label] = end - start return stats }) }, {}).tap(stats => { stats.runTime.total = stats.endTime - stats.startTime opts.log.silly('verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms`) }) }
module.exports = function (file, callback) { var content = JSON.parse(file.content); var deps = content.files; var now = parseInt(Date.now() / 1000, 10); var expire = content.expire || 604800; var defaultVersion = now - (now % expire); if (content.defaultVersionSuffix) { defaultVersion += ('' + content.defaultVersionSuffix); } file.addDependences(deps); Promise.reduce( file.getDependences(), function (versions, file) { return file.getVersion() .then(function (version) { if (now - version < expire) { versions[file.id] = version; } return versions; }); }, {} ) .then(function (version) { var config = {version: version}; config.defaultVersion = parseInt(defaultVersion, 10); file.content = JSON.stringify(config, null, 4); callback(null); }) .caught(callback); };