Skip to content

Instantly share code, notes, and snippets.

@mpj
Last active September 14, 2022 06:42
Show Gist options
  • Save mpj/ca167aad371c67372f3b to your computer and use it in GitHub Desktop.
Save mpj/ca167aad371c67372f3b to your computer and use it in GitHub Desktop.
This is the code from Monads - episode #21 of FunFunFunction (https://www.youtube.com/playlist?list=PL0zVEGEvSaeFSwPn06GKArptSxiP1Gff8)
const fetch = require('node-fetch')
const Bacon = require('baconjs')
function getInPortuguese(word) {
// Google Translate API is a paid (but dirt cheap) service. This is my key
// and will be disabled by the time the video is out. To generate your own,
// go here: https://cloud.google.com/translate/v2/getting_started
const apiKey =
'AIzaSyB4DyRHIsNhogQXmH16YKbZfR-lTXrQpq0'
const url =
'https://www.googleapis.com' +
'/language/translate/v2' +
'?key=' + apiKey +
'&source=en' +
'&target=pt' +
'&q=' + encodeURIComponent(word)
const promise = fetch(url)
.then(response => response.json())
.then(parsedResponse =>
parsedResponse
.data
.translations[0]
.translatedText
)
const stream = Bacon.fromPromise(promise)
return stream
}
const stream = new Bacon.Bus()
stream
.flatMap(word => getInPortuguese(word))
.map(word => word.toUpperCase())
.onValue(word => console.log(word))
stream.push('cat')
stream.push('meal')
stream.push('trumpet')
// Output of running this file will be:
// TROMBETA
// REFEIÇÃO
// GATO
@elias551
Copy link

elias551 commented Jul 4, 2017

@Em-Ant Why not use this ? :)

...
stream
  .flatMap(getInPortuguese)
  .map(String.prototype.toUpperCase.apply)
  .onValue(console.log)
...

@palashmon
Copy link

palashmon commented Sep 22, 2017

For learning purpose, I am using this code, without the need of setting up Google Translate API 😉

const portuguese = ['que', 'bonito', 'rir', 'pequeno', 'longe'];
const randomWord = arr => arr[Math.floor(Math.random() * (arr.length - 1))];
const getPortuguese = word => {
    const promise = Promise.resolve(`${word} ${randomWord(portuguese)}`);
    const stream = Bacon.fromPromise(promise);
    return stream;
};

Output using map():

Bacon.fromPromise({})
Bacon.fromPromise({})
Bacon.fromPromise({})

Output using flatMap():

CAT RIR
MEAL QUE
TRUMPET BONITO

FunFunFunction!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment