0

On my site I want to include a palindrome finder where you can drag in a .txt file and it will give you all the palindromes within it. I am able to read this data and log it in my console, but am unable to use the actual data. When I try to get using jquery it fails because it does not recognize the data as a string. I have included my code for better explanation.

HTML:

<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">

JS:

function dropHandler(ev) {
    console.log('File(s) dropped');
  
    // Prevent default behavior (Prevent file from being opened)
    ev.preventDefault();
  
    if (ev.dataTransfer.files) {
        let files = ev.dataTransfer.files;
        let data = "";
        file = files[0];
        if(file.type.indexOf("text") == 0){
            let reader = new FileReader();
            reader.onload = function(ev){
                data = ev.target.result;
                //console.log(data); GIVES ME CONTENTS OF FILE!
                //console.log(typeof data);
            }
            reader.readAsText(file);
            //console.log(typeof data);
            //$.get("/palindrome" + data, {}, function response(){
                //console.log(response);
            //});
        }
    }

}

CPP (I am using Crow backend)

CROW_ROUTE(app, "/palindrome/<string>")([](string data){
        crow::json::wvalue x;
        x = getPalindromes(data);
        return x;
});


/////////////////////////////
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "crow_all.h"

using namespace std;

//Globally declared map
unordered_map<string, bool> hashmap;

crow::json::wvalue getPalindromes(string data){
    crow::json::wvalue x;
    string word = "";
    for(int i = 0; i < data.size(); i++){
        if(data[i] == '\n'){
            hashmap.insert({word, true});
            word = "";
        }
        else{
            word += data[i];
        }
    }
    string temp;
    vector<string> words;
    int numValid = 0;
    for(auto& i: hashmap){
        temp = i.first;
        reverse(temp.begin(), temp.end());
        auto got = hashmap.find(temp);
        if(got != hashmap.end()){
            words.push_back(i.first);
            numValid++;
        }
    }
    x["words"] = words;
    x["numValid"] = numValid;
    return x;
}
NeonFire
  • 186
  • 2
  • 7
  • Does this answer your question? [get the data of uploaded file in javascript](https://stackoverflow.com/questions/16505333/get-the-data-of-uploaded-file-in-javascript) – Jared Smith Dec 30 '20 at 11:01
  • More specifically: https://stackoverflow.com/a/56737666/3757232 – Jared Smith Dec 30 '20 at 11:02
  • I suppose I should re-phrase the question. I have successfully read the data, which in this case would be a .txt file which would become a list of strings. How can I utilize this data? I want to look through each word – NeonFire Dec 30 '20 at 11:08
  • `textData.split('\n').forEach(line => line.split(/\s+/).forEach(word => doSomething(word)));` Although it looks like you are trying to pass it to the backend? Is there a reason why? How big is this file? – Jared Smith Dec 30 '20 at 11:12
  • The file is 400,000 lines, so I am using a C++ backend called Crow so I can use unordered maps to instantly find if the word is valid when read backwards. I have updated the c[pp part of the original question – NeonFire Dec 30 '20 at 11:15
  • In that case `const palindromes = textData.split('\n').flatMap(line => line.split(/\s+/).filter(word => word === word.split('').reverse().join('')));` I would just do it on the frontend. C++ is faster than JS but JS will still easily crank out 1mil+ ops/second and you'll lose more time on the transfer than you'll gain. That code splits the text data into an array on newlines, splits each line on spaces, splits each word into a char array, reverses it, joins it back to a string, and compares it to the original word. The flatMap flattens the sub-arrays into a single one. – Jared Smith Dec 30 '20 at 11:18
  • Thanks! I'm very new to JavaScript and assumed sending the data to the backend could be faster. But thank you for the info – NeonFire Dec 30 '20 at 11:26
  • You're welcome. I think Quentin was a little over-eager with the dupe hammer, and I've voted to reopen your question, so we'll see what happens. In any case hope that gets it for you. – Jared Smith Dec 30 '20 at 11:29
  • If I did want to have it on the backend how would I be able to send over that much data – NeonFire Dec 30 '20 at 11:30
  • You'd typically send it as JSON over AJAX, and I would just send the list of palindromes. Since you're using jQuery: `$.post({ url: '/some/url', data: JSON.stringify(palindromes) });`. Just make sure you have an appropriate POST route in your server-side framework set up to handle it. Oh, and do note that on the code I posted above the `.flatMap` method on arrays is pretty new, you'll have to polyfill for older browsers if you're worried about such. – Jared Smith Dec 30 '20 at 11:34

0 Answers0