Last active
February 11, 2016 08:31
-
-
Save kimhogeling/91bf0bed83c971204a68 to your computer and use it in GitHub Desktop.
Search Google Predictions with help of a given array and print them with tabs to copy paste into spreadsheets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created in Chrome. Uses `fetch` API and the high order functions `map` and `forEach`. | |
* Module `googlePredictions` reveals two functions `fetchAndPrint` and `formattedPrint`. | |
* method `fetchAndPrint` needs an {Array} argument containing {string} search words. | |
* example: `googlePredictions.fetchAndPrint(['adidas', 'puma', 'nike', 'apple']);` | |
* method `formattedPrint` assumes `fetchAndPrint` was already called and needs no arguments. | |
* Example `googlePredictions.formattedPrint();` | |
* This is helpful in case one or more rows could not be fetched, | |
* and the automatic print at `fetchAndPrint` was not called. | |
*/ | |
var googlePredictions = (function () { | |
'use strict'; | |
/* PUBLIC METHODS */ | |
function fetchAndPrint(searchWords) { | |
_searchWordsLength = searchWords.length; | |
searchWords.forEach(_fetchPredictionsFromGoogle); | |
} | |
function formattedPrint() { | |
var pretty = ''; | |
_endResult.sort(); | |
_endResult.forEach(function (row) { | |
row.forEach(function (cell) { | |
pretty += cell + '\t'; | |
}); | |
pretty += '\n'; | |
}); | |
console.log(pretty); | |
} | |
/* PRIVATE METHODS */ | |
function _fetchPredictionsFromGoogle(searchWord) { | |
if (typeof searchWord !== 'string') { | |
console.error('Given searchWord is not a string.', searchWord); | |
_searchWordsLength--; | |
return; | |
} | |
searchWord = encodeURIComponent(searchWord); | |
fetch('https://www.google.de/complete/search?sclient=psy-ab&site=&source=hp&q=' + searchWord + '&oq=&gs_l=&pbx=1&bav=on.2,or.&bvm=bv.113370389,d.ZWU&fp=1&biw=731&bih=705&dpr=2&pf=p&gs_rn=64&gs_ri=psy-ab&tok=1e3TgYJYRkzLSXqNxu5N8g&cp=6&gs_id=r&xhr=t&tch=1&ech=8&psi=GyC5VvKECMSqPL_mpHA.1454972955852.1') | |
.then(_checkStatusOfResponse) | |
.then(_readTextFromResponse) | |
.then(_extractRowFromResponseText) | |
.then(_printIfDone) | |
.catch(function (e) { console.error('Problem at "' + searchWord + '".', e) }); | |
} | |
function _checkStatusOfResponse(r) { | |
if (r.status < 200 && r.status >= 300) { | |
return Promise.reject(new Error(r.statusText)); | |
} | |
return Promise.resolve(r); | |
} | |
function _readTextFromResponse(r) { | |
return r.text(); | |
} | |
function _extractRowFromResponseText(rt) { | |
try { | |
var row = JSON.parse(JSON.parse(rt.replace('/*""*/', '')).d)[1].map(function(cell) { | |
return cell[0].replace('<b>', '').replace('</b>', ''); | |
}); | |
_endResult.push(row); | |
} catch (e) { | |
return Promise.reject(new Error('Problem extracting row from Google\'s response. It might be missing in the end result below.')); | |
} | |
} | |
function _printIfDone() { | |
if (_searchWordsLength === _endResult.length) { formattedPrint() } | |
} | |
var _endResult = [], _searchWordsLength = 0; | |
// Reveal public methods | |
return { | |
fetchAndPrint: fetchAndPrint, | |
formattedPrint: formattedPrint | |
}; | |
}()); | |
// Example: | |
googlePredictions.fetchAndPrint(['adidas', 'puma', 'nike', 'apple']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
'4 Wards','7 For All Mankind','Abahna','Absorba','Acronis','acuvue','Adidas','adidas by stella mccartney','adidas NEO','adidas originals','adidas SLVR','Adler','Adobe','Affliction','Ajungilak','Alba Moda','Alba Moda Rosso','Alba Moda Verde','Allrounder','Amaris','Ambria','American Apparel','American Tourister By Samsonite','Amplified','ana alcazar','Andy Warhol by Pepe Jeans','Anna Field','Anna Scholz','Annemarie Börlind','Antik Batik','AOK','Arabella','Aramis','armedangels','ARQUEONAUTAS','Ascari','asics','Authentic Underwear Le Jogger','Aveda','Avent','Azzaro','B.C. Best Connections','b2 by via appia','ba&sh','Babista','Babywalz','Baldessarini','Balenciaga','Barbour','Bäumler','Béaba','Beal','Beal','Beldivani','Bellybutton','Belmondo','Ben Sherman','Berghaus','Betty Barclay','Bikkembergs','Biotherm','Björn Borg','Blackberry','blend-a-med','Bloch','Blowfish','bob','Bob Der Baumeister','Boden','Bogner','Bogner Fire & Ice','Bogner Jeans','Bonita','Bose','Bottega Veneta','Boucheron','Bowers & Wilkins','Boxfresh','Boysen''s','Brax','Brax Golf','Bridgestone','Brita','Britney Spears','brønd','Brunotti','Bruuns Bazaar','Bugatti','Bulgari','Burberry','Burlington','Burt''S Bees','Bvlgari','BZR','C & A','C&A','Calida','Calvin Klein','Camaro','Camper','Campus','Canada Goose','Carl Gross','Carrera','Carrera Evolution','Carrera Go!!!','Cartoon Fashion','Casadei','Castaluna','Catimini','Catsan','Chanel','Cheer','Chillytime','Chipie','Chopard','Clarks','Clarks Originals','Claudio Ferrici','Cleptomanicx','Clinique','Clipper','Closed','Codello','Comptoir Sud Pacifique','Conley''s','Connemara','Corneliani','Craghoppers','Crumpler','Custo Barcelona','Dallmayr','Daniel Hechter','Data Becker','DC Shoes','Deerberg','Deichmann','Dell','Delta Light','Denim & Supply Ralph Lauren','Derhy','desiary','Desigual','Deuter','Devolo','Diamonfire','Diemer','Dimensione Danza','Dior','Dolce & Gabbana','Dolmar','Dr. Junghans','DRYKORN','Dyson','E-Plus','Early 20','Eastpak','Eat ants by Sanetta','ECCO','Ed Hardy','EDC by Esprit','Eddie Bauer','Elefanten','Emilio Pucci','Epson','Ermenegildo Zegna','Escada','Esprit','Estádio','Estée Lauder','Eterna','Etirel','Etro','Eucerin','Eurex By Brax','Eurostar','Falke','Feiyue','Fendi','Ferrari','Feuerwear','Filippa K','Fink','Firetti','Fishbone','Fiskars','Fissler','Fit-Z','Fjäll Räven','Flashlights','Flg Flashlights','Flik Flak','Floris','Floris van Bommel','Focus','Formano','Fortis','Fossil','Franklin & Marshall','French Connection','French Sole','Friis & Company','Furla','G-Star Raw','Gaastra','Gallus','Georgia Rose','Gerry Weber','Giesswein','Gil Bret','Gio Goi','Giorgio Armani','Givenchy','Goliath','Goosecraft','Greenality','Grey Connection','Grohe','Gsus Sindustries','Gucci','Guess','Guess By Marciano','Guess Jeans','Guess Kids','Guy Laroche','Haier','Hallhuber','Hanky Panky','Hansaplast','Hansgrohe','Hanwag','Happy Size','Happy Socks','Hark','Hattric','','Health Hoop','Heelys','Heine','Herma','Herman Miller','Hermès','hessnatur','Hilfiger Denim','Hirmer','HOM','Hummel','Hunkemöller','Hush Puppies','Hutschenreuther','Ikks','Illy','Imps & Elfs','Inwear','Irie Daily','iRobot','Irregular Choice','Issa','Ix Chel','J. Lindeberg','Jabra','Jack Wolfskin','Jacques Britt','JAKO-O','Jan Vanderstorm','Jette Joop','Jimmy Choo','Joe Browns','John Devin','John F. Gee','JOOP!','Joop! Bodywear','Joop! Casual','Joseph Joseph','Juicy Couture','Julia S.','Junghans','Juvena','K1x','Kafé Stigur','Kangaroos','Kanz','Karen Millen','KARHU','Kartell','Kaspersky','Kenneth Cole','Kenzo','Kesslord','Kettler','Khujo','Kidoki','Kipling','Klingel','Knirps','Kodak','Koncept by Koah','Koolaburra','Koziol','Kyocera','La Martina','LA PERLA','La Prairie','Lab Series','Lab Series For Men','LaCie','Lacoste','Lacoste LIVE','Lamarthe','Lancom','Lancôme','Lands'' End','Lascana','Laura Ashley','Laura Scott','Laurastar','Lavana','Lavazza','Le Coq Sportif','Le Jogger','Lego','Lego Castle','Lego City','Lego Creator','Lego Duplo','Lego Star Wars','Lego Technic','Leki','Levi''s','Lexmark','Lexware','LG','Liebeskind Berlin','Lief!','Lili Gaufrette','Linea Tesini','LITTLE MARC JACOBS','Liu Jo','Loake','Loewe','Loiza by Patrizia Pepe','Lolita Lempicka','Longchamp','Louis Poulsen','Love Moschino','Lowa','Luger','M.I.M','Mac','Maison Martin Margiela','Maison Scotch','Makita','Mammut','Mandarina Duck','Männersache by Liebeskind','Marc Aurel','Marc By Marc Jacobs','Marc Cain','Marc Jacobs','Marc O''Polo','Marco Donati','Marco Pecci','Marmot','Marni','Maui Wowie','Maxim','MaxMara','Mazine','McAfee','McKinley','McNeal','McNeill','Medion','Meindl','Melrose','Melvin & Hamilton','Merrel','Merrell','Mexx','Mey','Michael Kors','MICHAEL Michael Kors','Michelin','Mindjet','Mishumo','Miu Miu','mJ-1 by Wolfgang Joop','Molton Brown','Moncler','Montblanc','Moschino','Motocaddy','Mulberry','Multipolster','Multipower','Multipower Professional','Mustang','Mustang Shoes','Muubaa','Myla','Nachtmann','Narciso Rodriguez','Navigon','Neighborhood','Nero','Nespresso','Netgear','New Yorker','Nici','Nike','Nina von C.','Nivea','Nixon','Nokia','Norröna','Nuance','Nutricia','NYDJ','O.C.K.','O`Neill','o2','Oakley','OBOY','OBOY Streetwear','Octopus','Odlo','Oilily','Oliver Sweeney','Olsen','Omax','One True Saxon','Oregon Scientific','Otto Office Budget','Otto Office Premium','Otto Office Standard','Palmers','Paloma Picasso','Passigatti','Passport','Patrizia Pepe','Paul & Joe','Paul & Joe Sister','Paul Smith','Peak Performance','Penhaligon''S','Pennyblack','Pepe Jeans','Peter Kaiser','Petite Fleur','Peugeot','Philipp Plein','Philips Avent','Picnic','Piquadro','Playmobil','Plein Sud','Plein Sud Jeanius','Polo Ralph Lauren','Porsche','Porsche Design','Prada','Prada Parfums','Princesse tam tam','Pro Touch','Puma','Pussy Deluxe','QS by s.Oliver','Quiksilver','Ralph Lauren','Raymond Weil','Re-ject','Red or Dead','Redgreen','Reebok','Reebok Classic','Reisenthel','Richter','Rimowa','Rockgewitter','Rocxygen','Rodeo','Roland Schuhe','Rolex','s.Oliver','s.Oliver Time','Saeco','Salewa','Salvatore Ferragamo','Samoon','Samsonite','Sanetta','Sara Lindholm','Schlaraffia','Schöffel','Scotch & Soda','Scotch & Soda Shrunk','Scotch R''Belle','Scotch Shrunk','Seagate','See by Chloé','Seidensticker','Selecta','Sergio Rossi','Sheego','Shoepassion','Signum','Singh S. Madan','Sioux','Skagen','Slendertone','Sloggi','SLVR (adidas)','So Bin Ich','Sompex','Sonia Rykiel','Sony','Spanx','St. Jacques','Stairville','Stefanel','Steganos','Steiff','Steve Madden','Stockerpoint','Stratic','Street One','Strellson','Strellson Premium','Strellson Sportswear','Strenesse','Strenesse Blue','Strenesse Gabriele Strehle','Stressless','Studio La Perla','Suavinex','Superdry','Swarovski','Swissdent','Symantec','T-Mobile','Tag Heuer','Taifun','Talika','Tamaris','Tandberg','Tara Jarmon','Tatonka','Tautropfen','Taylor & Reece','Tecnolumen','Ted Baker','Teddy Smith','Tempur','Tessuto Zegna','Teva','Therm-A-Rest','Thierry Mugler','Think!','Thomas Sabo','Tiffany & Co.','Tiger Of Sweden','Tikamoon','Timbuk2','Tissot','Tivola','Tommee Tippee','Tommy Hilfiger','Tommy Hilfiger Tailored','Toms','Toms Shoes','TomTom','Topolino','Topper Dillon','Triangle by s.Oliver','Trigema','Trimilin','Triumph','Tw Steel','Ubisoft','UGG Australia','Ulla Popken','Under Armour','Unisa','Urbanears','Valerie Perrini','Valisere','Vamos-Schuhe','Van Cleef & Arpels','Van Laack','Velux','Venice Beach','Venture','Vera Mont','Vertbaudet','Very by Venice Beach','Via Appia','Via Appia Due','Viega','Vitra','Vivance','Vivance Dreams','Vivance Jewels','Vivien Caron','VM','Vodafone','Vogue (eyewear)','Voi Jeans','Volcom','Vorwerk','Vsct','Wenz','Whiskas','WMF','Wolford','wolverine','World Of Warcraft','X-Bionic','X-Two','Xerox','Zalando Essentials','Zassenhaus','Zegna','Zegna Sport','ZENGGI','Zeppelin','Zign Shoes','Zumba','Zweibrüder'