<commit_before>const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });<commit_msg>feat(functions): add a search function<commit_after>'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.search = functions.https.onRequest(function search(req, res) {
  const searchTerm = req.query.q;
  admin.database().ref('/books').once('value').then(function data(snapshot) {
    const valAsArray = convertToArray(snapshot.val());
    const result = filterByName(searchTerm, valAsArray);
    res.json({ result: result });
  }).catch(function onError(error) {
    res.json(error);
  });
});

function convertToArray(val) {
  const array = [];
  for (const key in val) {
    array.push(Object.assign({ uid: key }, val[key]));
  }

  return array;
}

function filterByName(term = '', values = []) {
  const search = createSearchExp(term);
  return values.filter(n => search.test(n.title));
}

function createSearchExp(val = '') {
  const exp = val.replace(/ /g, '.*');
  return new RegExp(`.*${exp}.*`, 'gi')
}
{'fraction_non_alphanumeric': 0.17751479289940827, 'fraction_numerical': 0.0, 'mean_word_length': 4.545081967213115, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2836134', 'n_tokens_mistral': 409, 'n_tokens_neox': 410, 'n_words': 86}