exports.search = query=> { var connection = new Connection(); return connection.connect() .then(connection.collection.bind(connection, Tables.MY_PLACES_2)) .then(coll=> { var regex = new RegExp(query, "gi"); return Promise.all([ coll.find({name: regex}, {name: 1, _id: 1}).sort({score: -1}).limit(3).toArray() .then(R.map(place=>Object.assign({seo_url:"/" + SeoUrl.createURL(place.name)},place))) , coll.find({category_list: regex}, {category_list: 1}).sort({score: -1}).limit(3).toArray() .then(R.compose(R.map(cat=> { return { seo_url: "/" + SeoUrl.createURL(cat) , name: cat , query: cat } }), R.uniq, R.filter(cat=>cat.match(regex)), R.flatten, R.map(R.prop("category_list")))) ]) }) .then(([places,categories])=> { return { body: { places , categories } } }) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) };
update: (storeName, game, cb) => { storage(store).read(storeName, r.compose( r.tap(cb), r.tap(games => { store[storeName] = JSON.stringify(games) }), r.append(game), r.reject(r.propEq('id', game.id)))) },
function importToMDB() { Promise.resolve(JSON.parse(fs.readFileSync("imprese-google-2.json"))) .then(R.compose( R.map(impresa=>impresa.google.results) , R.filter(impresa=> { return impresa.google.results && impresa.google.results.length > 0 }))) .then(R.flatten) .then(imprese=> { var connection = new Connection(); return connection.connect() .then(db=> { var coll = db.collection(Tables.GOOGLE_PLACES); return Promise.all(imprese.map(impresa=>{ return coll.findOneAndUpdate({place_id:impresa.place_id},{$set:impresa},{upsert:true}) })) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) }) }) .then(R.tap(_=>process.exit(0))) .catch(R.tap(_=>process.exit(1))); }
test("Monads as programmable commas", function () { // map :: (ObjectA -> ObjectB), Monad -> Monad[ObjectB] const map = R.curry((f, container) => container.map(f)); // chain :: (ObjectA -> ObjectB), M -> ObjectB const chain = R.curry((f, container) => container.chain(f)); const lift = R.curry((f, obj) => Maybe.fromNullable(f(obj))); const trace = R.curry((msg, obj) => console.log(msg)); const showStudent = R.compose( R.tap(trace('Student printed to the console')), map(R.tap(console.log)), //-> Using R.tap to simulate the side effect (in the book we write to the DOM) R.tap(trace('Student info converted to CSV')), map(csv), map(R.props(['ssn', 'firstname', 'lastname'])), R.tap(trace('Record fetched successfully!')), chain(findStudent), R.tap(trace('Input was valid')), chain(checkLengthSsn), lift(cleanInput) ); let result = showStudent('444-44-4444').getOrElse('Student not found!'); expect(result).toEqual('444-44-4444,Alonzo,Church'); });
.then(db=> { var coll = db.collection(Tables.GOOGLE_PLACES); return Promise.all(imprese.map(impresa=>{ return coll.findOneAndUpdate({place_id:impresa.place_id},{$set:impresa},{upsert:true}) })) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) })
.then(db=> { var placesColl = db.collection(Tables.MY_PLACES_2); return placesColl.find({category_list: "cinema"}, {_id: 1}).toArray() .then(cinemas=> { cinemas = cinemas.map(cinema=>cinema._id.toString()); return cinemas.includes(id); }) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) });
(jsFileMetaData) => pipeP( prop('contents_url'), getJsonFromHttp, tap(ej), prop('download_url'), tap(ej), getBodyFromHttp, commentOutEverything, (newContents) => ({newContents, jsFileMetaData}) // TODO remove this weird device )(jsFileMetaData)
exports.findById = id=> { var connection = new Connection(); return connection.connect() .then(connection.collection.bind(connection, Tables.MY_PLACES_2)) .then(coll=> { return coll.findOne({_id: ObjectId(id)}); }) .then(R.tap(_=>connection.db.close())) .then(mapDetailPlace) .catch(R.tap(_=>connection.db.close())) };
exports.findMyPlaceByFacebookId = id_facebook=> { var connection = new Connection(); return connection.connect() .then(connection.collection.bind(connection, Tables.MY_PLACES_2)) .then(coll=> { return coll.findOne({id_facebook}); }) .then(R.tap(_=>connection.db.close())) .then(mapDetailPlace) .catch(R.tap(_=>connection.db.close())) };
module.exports = function(user) { logger.log('info', 'slack details', user); return verifyDependencies() .then(function() { return new webdriver.Builder().forBrowser('chrome').build(); }) .then(R.tap(R.invoke('get', [URI.slack]))) .then(login) .then(R.tap(R.invoke('get', [URI.slackInvites]))) .then(R.curry(fillUserInformation)(user)) .then(successMessage) .catch(errorMessage); };
.then( places =>{ var connection=new Connection(); return connection.connect() .then(connection.collection.bind(connection,Tables.GOOGLE_PLACES)) .then(coll=>{ var promises = places.map(place=> { return coll.findOneAndUpdate({place_id:place.place_id},{$set:place},{upsert:true}) }); return Promise.all(promises); }) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) })
const taim = (...args) => { const color = chalk[nextColor()]; const [val, label] = getArgs(...args); return cond([ [ hasThenFn, (val) => { const start = process.hrtime(); val.then(() => { printDuration(start, color, label); }); return val; } ], [ isFunctionOrAsyncFunction, (val) => (...args) => { const start = process.hrtime(); const res = val(...args); const fn = () => printDuration(start, color, label); if (res && hasThenFn(res)) res.then(fn); else fn(); return res; } ], [ T, tap(val => { println(process.stderr, `taim error: input should be a async function, function, or thenable, instead got a ${type(val)}`); }) ] ])(val); };
.then(function (exists) { log_1.log('found %s ?', exePath, exists); if (!exists) { throw notInstalledErr("Browser " + name + " file not found at " + exePath); } // on Windows using "--version" seems to always start the full // browser, no matter what one does. var args = [ 'datafile', 'where', "name=\"" + doubleEscape(exePath) + "\"", 'get', 'Version', '/value' ]; return execa('wmic', args) .then(function (result) { return result.stdout; }) .then(ramda_1.trim) .then(ramda_1.tap(log_1.log)) .then(getVersion) .then(function (version) { log_1.log("browser %s at '%s' version %s", name, exePath, version); return { name: name, version: version, path: exePath }; }); })
/* Returns the last commit id */ function lastCommitId (options) { options = options || {} var resultId function addBuildInfo (id) { resultId = id try { return utils.addBuildInfo(options, id) } catch (e) { console.error('Problem adding build information to commit SHA') console.error(e.message) return utils.defaultBuildInfo(id) } } return findCommit() .then(cleanOutput) .then( R.tap(function (id) { console.log('last commit:', id) resultId = id }) ) .then(addBuildInfo) .then(function (build) { return saveIntoFile(options.file, build) }) .then(function () { return resultId }) }
test('when Pagarme is offline and encryption key is used', () => pagarme.client.connect({ encryption_key: 'nwdu91jd9', options: { baseURL: 'http://a-big-non-existent-website-from-interwebs.nope', }, }) .then(tap(client => expect(client.authentication.encryption_key).toBe('nwdu91jd9'))))
export const multivarka = (...reqBuildChain) => compose( tap(startRequest), over(lensProp('query'), RWhen( pathSatisfies(equals(0), ['$and', 'length']), omit(['$and']) )), ...reqBuildChain )(RequestType);
const showStudent = (ssn) => Maybe.fromNullable(ssn) .map(cleanInput) .chain(checkLengthSsn) .chain(findStudent) .map(R.props(['ssn', 'firstname', 'lastname'])) .map(csv) .map(R.tap(console.log)); //-> Using R.tap to simulate the side effect (in the book we write to the DOM)
function getFacebookPlacesCollection() { var connection = new Connection(); return connection.connect() .then(_=>Tables.FACEBOOK_PLACES) .then(connection.collection.bind(connection)) .then(coll=> { return coll.find().toArray() }) .then(R.tap(_=>connection.db.close())) }
exports.eventi = ({start_time, end_time, limit})=> { var connection = new Connection(); return connection.connect() .then(db=> { var myPlaces = db.collection(Tables.MY_PLACES_2); var myEvents = db.collection(Tables.MY_EVENTS); var query = {start_time: {$gte: start_time.getTime()}}; if (end_time) { query.end_time = {$lte: end_time.getTime()}; } return Promise.all([ myPlaces.find().toArray() , myEvents.find(query).limit(limit).sort({start_time:1}).toArray() ]) }) .then(getEvents()) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())); };
function checkSensitiveFiles (options) { var start if (is.array(options)) { log('assuming got array of filenames to check for leaked data') start = Promise.resolve(options) } else { start = collectFiles(options) } return start .then(leaveSensitive) .then(R.tap(print)) .then(findLeakedData) }
exports.findEventById = id=> { var connection = new Connection(); return connection.connect() .then(connection.collection.bind(connection, Tables.MY_EVENTS)) .then(coll=> coll.findOne({_id: ObjectId(id)})) .then(event=> { var myPlaceColl = connection.db.collection(Tables.MY_PLACES_2); var id_owner = event.owner && event.owner.id; var id_place = event.place && event.place.id; return Promise.all([ id_owner ? myPlaceColl.findOne({id_facebook: id_owner}) : Promise.resolve(null), id_place ? myPlaceColl.findOne({id_facebook: id_place}) : Promise.resolve(null) ]).then(([owner,place])=> { var description = formatDescription(event.description); if (!place && owner) { place = owner; } else if (!owner && place) { owner = place; } else if (!place && !owner) { place = owner = {}; } place.seo_url = `/${SeoUrl.createURL(place.name)}`; owner.seo_url = `/${SeoUrl.createURL(owner.name)}`; return Object.assign({ image: R.view(R.lensPath(['cover', 'source']), event) }, event, { description , raw_description: event.description , owner , place }) }); }) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())) };
.then((company) => { const ek = company.encryption_key.test return pagarme.client.connect({ encryption_key: ek }) .then(tap(client => expect(client.authentication.encryption_key) .toBe(ek))) .then(client => client.transactions.calculateInstallmentsAmount({ amount: 1, interest_rate: 100, })) .then(result => expect(result).toBeTruthy()) .catch(err => expect(err.message).not.toBe('You must supply a valid key')) })
exports.findByChannel = function (id, options = {limit: 12, filters: []}) { var connection = new Connection(); return connection.connect() .then(db=> { var my_places = db.collection(Tables.MY_PLACES_2); var query = {}; if (id) { var _regexp = new RegExp(id, "gi"); query = {category_list: {$all: options.filters.concat([_regexp])}}; } return my_places.find(query) .sort({score: -1}) .limit(options.limit) .toArray() .then(eliminaEccezioni(id)) }) .then(R.tap(_=>connection.db.close())) .then(R.map(mapDetailPlace)) .catch(R.tap(_=>connection.db.close())) };
exports.eventiByPlace = ({start_time, end_time, limit, id_place})=> { var connection = new Connection(); return connection.connect() //.then(connection.collection.bind(connection, Tables.MY_EVENTS)) .then(db=> { var myPlaces = db.collection(Tables.MY_PLACES_2); var myEvents = db.collection(Tables.MY_EVENTS); return myPlaces.findOne({_id: ObjectId(id_place)}).then(my_place=> { var time_query = {start_time: {$gte: start_time.getTime()}}; if (end_time) { time_query.end_time = {$lte: end_time.getTime()}; } return myEvents.find( { $and: [ time_query, { $or: [ {"owner.id": {$in: my_place.id_facebook}} , {"place.id": {$in: my_place.id_facebook}} ] } ] } ).limit(limit).sort({start_time:1}).toArray() .then(my_events=> { return [[my_place], my_events] }) }) }) .then(getEvents()) .then(R.tap(_=>connection.db.close())) .catch(R.tap(_=>connection.db.close())); };
const taimCb = (...args) => { const color = chalk[nextColor()]; const [val, label] = getArgs(...args); return cond([ [ isFunction, (val) => (...args) => { const origCb = last(args); const start = process.hrtime(); val(...concat(init(args), [ (...cbArgs) => { printDuration(start, color, label); origCb(...cbArgs); } ])); } ], [ T, tap(val => { println(process.stderr, `taim error: input should be a function, instead got a ${type(val)}`); }) ] ])(val); };
// returns list of unique changed file after the given commit function changedFilesAfter (sha, branch) { if (!branch) { branch = 'master' } la(is.unemptyString(sha), 'missing from SHA', sha) debug('changed files after %s', sha) debug('on branch %s', branch) return commits .after(sha, branch) .then(ids) .then( R.tap(list => { debug('commits') debug(list) }) ) .then(stats) .then(wait) .then(changes) .then(justFiles) }
chain, prop, pick, propEq, reject, or, tap, curry, merge, identity, sortBy, head, __ } from 'ramda'; const log = tap(console.log.bind(console)); //const error = tap(console.error.bind(console)); const error = (error) => { console.log('Error', error); }; var currentMapMaker; var currentLocation; var apiOptions = { maxResults: 10, distance: 10 }; var geoOptions = {
module.exports = function ($firebaseAuth, firebaseApp, firebaseUrl, empiricalBaseURL, $http, localStorageService) { var firebaseTokenUrl = empiricalBaseURL.replace(/\/?$/, '/firebase_tokens') + '?app=' + firebaseApp; var authObj, offAuth; // offAuth = handler for disabling function fetchToken() { return $http.post(firebaseTokenUrl).then(function success (response) { return response.data.token; }, function error (response) { console.log('an error occurred while fetching the firebase token: ', response); }); } function storeToken(token) { localStorageService.set('token', token); } function resetToken() { console.log('resetting the token'); storeToken(null); } function getCached(prop) { return localStorageService.get(prop); } // If a token is not provided, fetch and store it. var maybeFetchToken = R.ifElse(R.not, R.pipeP(fetchToken, R.tap(storeToken)), R.identity); var handleErrors; function firebaseAuthWithToken(token) { // authObj.$onAuth() return authObj.$authWithCustomToken(token).then(R.identity, handleErrors); } var fetchAndAuthWithToken = R.pipeP(maybeFetchToken, firebaseAuthWithToken); var resetAndFetch = R.pipeP(resetToken, fetchAndAuthWithToken); // If token is expired, try to re-fetch and auth again. handleErrors = R.cond([R.propEq('code', 'EXPIRED_TOKEN'), resetAndFetch], [R.propEq('code', 'INVALID_TOKEN'), resetAndFetch], [R.T, R.identity]); // Fall through to error handlers further down the promise chain. var reAuthIfLoggedOut = R.ifElse(R.not, fetchAndAuthWithToken, R.identity); function authenticate() { if (offAuth) { console.log('disabling auth callback'); offAuth(); } resetToken(); var ref = new Firebase(firebaseUrl); authObj = $firebaseAuth(ref); offAuth = authObj.$onAuth(reAuthIfLoggedOut); return fetchAndAuthWithToken(getCached('token')); } return { authenticate: authenticate }; };
function fileStatus () { return exec(cmd) .then(R.tap(log)) .then(stdoutToGroup) .then(R.tap(log)) }
const debug = msg => R.tap(R.partial(log, [msg]));