Calculs avec javascript

Fermé
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020 - Modifié le 27 mars 2020 à 11:36
jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 - 27 mars 2020 à 19:56
Bonjour à tous,

Je travail sur un projet perso en code javascript.
Il s'agit d'un compteur de mots.
Je suis parti sur un code "opensource" et je n'arrive pas à apporter quelques modifications.
J'ai avoir la possibilité de choisir un multiplicateur au nombre de mots trouvés.
Par exemple : 156 (mots) et choisir avec une combobox X2, ou X3. Le résultat serait alors affiché dans une nouvelle zone : résultat ► xxxxx .
Et ensuite avec deux cases à cocher (l'une ajoute +1 et l'autre ajout +2)
ça parait simple à d'écrire, mais je galère grave... :-(

Merci pour votre aide,
Fichiers source : https://we.tl/t-1CZnWsi8wU

/*
 **
 ** User stories:
 ** - Shows number of characters, words, sentences, paragraphs - Done
 ** - Show reading time - Done
 ** - Show keyword count - Done
 ** - Show reading level (Optional - how?) - Done
 ** - Above data should change/appear on every keypress - Done
 **
 */

// Readability (Mashape) API Key for testing: PQ4FOFuaR6mshI6qpnQKQvkDZQXjp1o6Zcqjsnug7GvNggTzUE

"use strict";
var input = document.querySelectorAll('textarea')[0],
  characterCount = document.querySelector('#characterCount'),
  wordCount = document.querySelector('#wordCount'),
  sentenceCount = document.querySelector('#sentenceCount'),
  paragraphCount = document.querySelector('#paragraphCount'),
  readingTime = document.querySelector('#readingTime'),
  readability = document.querySelector('#readability'),
  keywordsDiv = document.querySelectorAll('.keywords')[0],
  topKeywords = document.querySelector('#topKeywords');

// updating the displayed stats after every keypress
input.addEventListener('keyup', function() {
  
  //keeping the console clean to make only the latest data visible
  console.clear();
  

  // character count
  // just displaying the input length as everything is a character
  characterCount.innerHTML = input.value.length;
  

  // word count using \w metacharacter - replacing this with .* to match anything between word boundaries since it was not taking 'a' as a word.
  // this is a masterstroke - to count words with any number of hyphens as one word
  // [-?(\w+)?]+ looks for hyphen and a word (we make both optional with ?). + at the end makes it a repeated pattern
  // \b is word boundary metacharacter
  var words = input.value.match(/\b[-?(\w+)?]+\b/gi);
  // console.log(words);
  if (words) {
    wordCount.innerHTML = words.length;
  } else {
    wordCount.innerHTML = 0;
  }


  // sentence count	using ./!/? as sentense separators
  if (words) {
    var sentences = input.value.split(/[.|!|?]+/g);
    console.log(sentences);
    sentenceCount.innerHTML = sentences.length - 1;
  } else {
    sentenceCount.innerHTML = 0;
  }


  // paragraph count from http://stackoverflow.com/a/3336537
  if (words) {
    // \n$ takes care of empty lines: lines with no characters, and only \n are not paragraphs
    // and need to be replaced with empty string
    var paragraphs = input.value.replace(/\n$/gm, '').split(/\n/);
    paragraphCount.innerHTML = paragraphs.length;
  } else {
    paragraphCount.innerHTML = 0;
  }
  // console.log(paragraphs);


  // reading time based on 150 words/minute
  if (words) {
    var seconds = Math.floor(words.length *  60 / 150);
    // need to convert seconds to minutes and hours
    if (seconds > 59) {
      var minutes = Math.floor(seconds / 60);
      seconds = seconds - minutes*60;
      readingTime.innerHTML = minutes + "m "+ seconds + "s";
    } else {
      readingTime.innerHTML = seconds + "s";
    }
  } else {
    readingTime.innerHTML = "0s";
  }


  // finding out top keywords and their count
  // step-1: remove all the stop words
  // step-2: form an object with keywords and their count
  // step-3: sort the object by first converting it to a 2D array
  // step-4: display top 4 keywords and their count
  
  if (words) {
    
    // step-1: removing all the stop words
    var nonStopWords = [];
    var stopWords = ["à","allô","aucuns","auriez","auxdits","aviez","ayons","bof","çà","certaines","chez","comment","da","desquels","deviez","devras","doit","dues","dût","es","êtes","eurêka","excepté","fouchtra","fûmes","ho","hurrah","laquelle","leur","mazette","mâtin","ne","nulle","or","outre","pas","plein","pourraient","pourvu","pouviez","puis","pussent","que","quoi","saperlipopette","serait","sien","sommes","ta","telles","touchant","une","veuillez","voilà","voudrez","voulante","voulue","vôtre afin","alors","auquel","aurions","auxquelles","avions","aïe","boum","car","certains","chic","concernant","dans","devaient","devions","devrez","doive","duquel","eh","et","étiez","eus","eûmes","furent","fût","holà","hé","le","leurs","me","miséricorde","ni","nulles","ôté","palsambleu","patatras","plouf","pourrais","pouvaient","pouvions","puisque","put","quel","quoique","sapristi","seras","sienne","son","tandis","tels","tous","unième","veuillons","vos","voudriez","voulantes","voulues","vôtres ah","apr.","aura","aurons","auxquels","avoir","bah","bravissimo","ce","ces","chiche","contre","de","devais","devoir","devriez","doivent","durant","elle","étaient","étions","eusse","eût","fus","fûtes","hop","il","ledit","lorsque","merci","moi","nonobstant","nuls","ou","pan","pechère","plus","pourrait","pouvais","pouvoir","puisse","pécaïre","quelle","rataplan","sauf","serez","siennes","sont","tant","tes","tout","unièmes","veulent","votre","voudrions","voulants","voulurent","zut ai","as","aurai","auront","avaient","avons","basta","bravo","ceci","cet","chouette","corbleu","debout","devait","devons","devrions","doives","durent","elles","étais","être","eussent","eûtes","fusse","grâce","hormis","ils","lequel","lui","merde","moins","nos","ô","où","par","pendant","plusieurs","pourras","pouvait","pouvons","puissent","pût","quelles","revoici","se","seriez","siens","sous","taratata","tien","toute","v'lan","veut","voudra","voudrons","voulez","voulus","aie","attendu","auraient","autant","avais","ayant","beaucoup","ç'a","cela","cette","chut","coucou","depuis","devant","devra","devrons","donc","dus","en","était","eu","eusses","évohé","fussent","ha","hors","jarnicoton","les","là","mes","mon","notre","oh","ouais","parbleu","peu","pouah","pourrez","pouvant","psitt","puisses","qq.","quelqu'un","revoilà","selon","serions","sinon","soyez","tayaut","tienne","toutes","va","veux","voudrai","voudront","vouliez","voulussent","aient","au","aurais","autre","avait","ayante","bernique","ç'aura","celle","ceux","ciao","couic","des","devante","devrai","devront","dont","dussent","encontre","étant","eue","eussiez","évoé","fusses","hein","hou","je","lesdites","ma","mien","morbleu","nôtre","ohé","ouf","parce","peuchère","pour","pourriez","pouvante","pst","puissiez","qqch.","quelqu'une","rien","sera","serons","soi","soyons","taïaut","tiennes","tu","vers","via","voudraient","voulaient","voulions","voulut","aies","aucun","aurait","autres","avant","ayantes","bien","ç'aurait","celles","chacun","clic","crac","desdites","devantes","devraient","dia","du","dut","endéans","étante","eues","eussions","fi","fussiez","hem","hourra","jusque","lesdits","made","mienne","motus","nôtres","olé","ouille","pardi","peut","pourquoi","pourrions","pouvantes","pu","puissions","qqn","quels","sa","serai","seront","soient","stop","te","tiens","tudieu","veuille","vivement","voudrais","voulais","vouloir","voulût","ait","aucune","auras","aux","avec","ayants","bigre","ç'avait","celui","chacune","clac","cric","desdits","devants","devrais","diantre","dudit","dès","entre","étantes","euh","eut","fichtre","fussions","hep","hue","la","lesquelles","mais","miennes","moyennant","nous","on","oust","pardieu","peuvent","pourra","pourrons","pouvants","pue","purent","quand","qui","sacristi","seraient","ses","sois","suis","tel","toi","turlututu","veuillent","vlan","voudrait","voulait","voulons","vous","al.","aucunes","aurez","auxdites","avez","ayez","bis","ça","cependant","chaque","comme","crénom","desquelles","devez","devrait","dois","due","dû","envers","étants","eurent","eux","fors","fut","heu","hum","ladite","lesquels","malgré","miens","na","nul","ont","ouste","parmi","peux","pourrai","pourront","pouvez","pues","pus","quant","quiconque","sans","serais","si","soit","sur","telle","ton","un","veuilles","voici","voudras","voulant","voulu","vu"];
    for (var i = 0; i < words.length; i++) {
      // filtering out stop words and numbers
      if (stopWords.indexOf(words[i].toLowerCase()) === -1 && isNaN(words[i])) {
        nonStopWords.push(words[i].toLowerCase());
      }
    }
    // console.log(nonStopWords);

    // step-2: forming an object with keywords and their count
    var keywords = {};
    for (var i = 0; i < nonStopWords.length; i++) {
      // checking if the word(property) already exists
      // if it does increment the count otherwise set it to one
      if(nonStopWords[i] in keywords) {
        keywords[nonStopWords[i]] += 1;
      } else {
        keywords[nonStopWords[i]] = 1;
      }
    }
    
    // step-3: sorting the object by first converting it to a 2D array
    var sortedKeywords = [];
    for (var keyword in keywords){
      sortedKeywords.push([keyword, keywords[keyword]])  
    }
    sortedKeywords.sort(function(a, b) {return b[1] - a[1]});
    // console.log(sortedKeywords);

    // step-4: displaying top 4 keywords and their count
    topKeywords.innerHTML = "";
    for (var i = 0; i < sortedKeywords.length && i < 4; i++) {
      var li = document.createElement('li');
      li.innerHTML = "<b>" + sortedKeywords[i][0] + "</b>: " + sortedKeywords[i][1];
      topKeywords.appendChild(li);
    }
  }

  // displaying top keywords only if there is a word in the text area
  if (words) {
    keywordsDiv.style.display = "block";
  } else {
    keywordsDiv.style.display = "none";
  }
  
});


// readability level using readability-metrics API from Mashape
readability.addEventListener('click', function() {
  
  // placeholder until the API returns the score  
  readability.innerHTML = "Fetching score...";

  var requestUrl = "https://ipeirotis-readability-metrics.p.mashape.com/getReadabilityMetrics?text=";
  var data = input.value;

  var request = new XMLHttpRequest();
  request.open('POST', encodeURI(requestUrl + data), true);
  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  request.setRequestHeader("X-Mashape-Authorization", "PQ4FOFuaR6mshI6qpnQKQvkDZQXjp1o6Zcqjsnug7GvNggTzUE");
  request.send();

  request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      readability.innerHTML = readingEase(JSON.parse(this.response).FLESCH_READING);
    } else {
      // We reached our target server, but it returned an error
      readability.innerHTML = "Not available.";
    }
  };

  request.onerror = function() {
    // There was a connection error of some sort
    readability.innerHTML = "Not available.";
  };
});

// function to convert FLESCH READING SCORE into meaningful string.
function readingEase(num) {
  switch(true) {
    case (num <= 30):
      return "Readability: College graduate.";
      break;
    case (num > 30 && num <= 50):
      return "Readability: College level.";
      break;
    case (num > 50 && num <= 60):
      return "Readability: Lycée.";
      break;
    case (num > 60 && num <= 70):
      return "Readability: 8th - 9th grade.";
      break;
    case (num > 70 && num <= 80):
      return "Readability: 7th grade.";
      break;
    case (num > 80 && num <= 90):
      return "Readability: 6th grade.";
      break;
    case (num > 90 && num <= 100):
      return "Readability: 5th grade.";
      break;
    default:
      return "Not available.";
      break;
  }
}



3 réponses

jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 4 694
27 mars 2020 à 11:34
Bonjour,

Sans nous montrer le code concerné (ce que tu as déjà commencé à faire....)
cela va être compliqué de te répondre.

NB: Pour poster ton code, merci d'utiliser les balises de code
Explication ( à lire en entier !! ) disponible ici : https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code
1
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
27 mars 2020 à 12:40
J'ai mis le code en balise suivant vos recommandations Jordane45, merci.
0
jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 4 694 > nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
27 mars 2020 à 14:14
OK.
Et pour la partie Html ?
Qu'as tu commencé à faire exactement ?
Sur quoi bloques tu précisément ?

Ici on ne fait pas le travail à votre place... mais on veut bien aider à corriger en cas de difficultés.
0
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
27 mars 2020 à 15:03
<!DOCTYPE html>
<html>

<head>
  <title>JS</title>
  <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <meta name="description" content="A word counter built in HTML/CSS/JS. Shows number of characters, words, reading time and readability score. Also generates a list of top keywords.">
</head>

<body>
  <div class="container">
    <h1>JS</h1>
    <textarea placeholder="Collez ici..."></textarea>
	
	<div class="right">
	<a href="javascript:window.location.reload()">Réinitialiser JS</a>
	</div>

    <div class="output row">
      <div>DURÉE ► <span id="readingTime">0</span></div>
	  
      <div>NOMBRE DE MOTS ► <span id="wordCount">0</span></div>
    </div>
    <div class="output row">
      <div>PHRASES ► <span id="sentenceCount">0</span></div>
      <div>PARAGRAPHES ► <span id="paragraphCount">0</span></div>
    </div>
    <div class="output row">
      <div>CHARACTÈRES ► <span id="characterCount">0</span></div>
      <div id="readability">Show readability score.</div>
    </div>
    <div class="keywords">
      Mots les plus utilisés :
      <ul id="topKeywords">
      </ul>
    </div>
  </div>
  <script type="text/javascript" src="js/word-counter.js"></script>
</body>

</html>


Oui j'ai travaillé sur le html. le voici propre.
Je n'arrive pas mettre en place les calculs.
En fait j'aimerai pouvoir calculer un prix sur 156 (mots) avec des options.

Par exemple : choisir dans une combo " texte poésie " ou "article de blog"
Si "poésie" est sélectionné :
0.80 centimes le mot si < 100 mots,
0.75cts si > 100 mots < 200 mots
et 0.50cts si > 200 mots.

un article de blog le prix mots serait différent
0.70 centimes le mots si < 100 mots,
0,65cts si > 100 mots < 200 mots
et 0.60cts si > 200 mots.
Et afficher le prix dans une nouvelle zone : Prix ► xxxxx €.

Et avoir deux cases à cocher qui modifieraient le résultat trouvé (une case qui ajoute +10€ et l'autre ajoute +20€)
0
jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 4 694
27 mars 2020 à 15:17
Je ne vois ni les cases à cocher... ni l'endroit où tu veux afficher ton prix... ni le code que tu as déjà essayé de réaliser pour faire ce calculs.
0
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
27 mars 2020 à 15:21
Je ne sais pas du tout comment on fait ça. J'ai essayé des bouts de codes depuis hier soir trouvé sur internet, depuis je m'arrache les cheveux...
Hier soir j'ai abandonné et me suis couché pour reprendre ce matin.
SI j'avais le code, je pourrais rajouter autant d'options que je veux en reprenant et comprenant la structure du code.
0
jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 4 694
Modifié le 27 mars 2020 à 15:29
Tu peux au moins faire le html...
La liste déroulante (ta "combo")
https://developer.mozilla.org/fr/docs/Web/HTML/Element/select

Les cases à cocher :
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox

Sans oublier de mettre un ID à chaque élément qu'il faudra ensuite manipuler via le javascript.

Pour ce qui est du code ensuite,

j'ai essayé des bouts de codes depuis hier soir trouvé sur internet

Il ne faut pas prendre des bouts de code au hasard et espérer que ça marche du premier coup...... il faut plutôt faire en sorte de les comprendre.
Pour ça, il existe de nombreuses documentations sur le net et des tutos pour apprendre le javascript.

Cibler un élément via son id :
https://developer.mozilla.org/fr/docs/Web/api/Document/getElementById

Faire un test
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/if...else

etc...
0
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020 > jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024
27 mars 2020 à 15:37
C'est fait :-)

<!DOCTYPE html>
<html>

<head>
  <title>JS</title>
  <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <meta name="description" content="A word counter built in HTML/CSS/JS. Shows number of characters, words, reading time and readability score. Also generates a list of top keywords.">
</head>

<body>
  <div class="container">
    <h1>JS</h1>
    <textarea placeholder="Collez ici..."></textarea>
	
	<div class="right">
	<a href="javascript:window.location.reload()">Réinitialiser JS</a>
	</div>

    <div class="output row">
      <div>DURÉE ► <span id="readingTime">0</span></div>
	  
      <div>NOMBRE DE MOTS ► <span id="wordCount">0</span></div>
    </div>
    <div class="output row">
      <div>PHRASES ► <span id="sentenceCount">0</span></div>
      <div>PARAGRAPHES ► <span id="paragraphCount">0</span></div>
    </div>
    <div class="output row">
      <div>CHARACTÈRES ► <span id="characterCount">0</span></div>
      <div id="readability">Show readability score.</div>
    </div>
	
	<label for="pet-select">Type de texte:</label>

<select name="type" id="type-select">
    <option value="">--Choisir une option--</option>
    <option value="poesie">Poésie</option>
    <option value="blog">Blog</option>
</select>
	<div>
  <input type="checkbox" id="option10" name="option10"
         checked>
  <label for="option10">+10€</label>
</div>

<div>
  <input type="checkbox" id="option20" name="option20">
  <label for="option20">+20€</label>
</div>
    <div class="keywords">
      Mots les plus utilisés :
      <ul id="topKeywords">
      </ul>
    </div>
  </div>
  <script type="text/javascript" src="js/word-counter.js"></script>
</body>

</html>
0
jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024 4 694 > nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
Modifié le 27 mars 2020 à 15:51
Un exemple de ce qui est possible de faire
<!DOCTYPE html>
<html>

<head>
  <title>JS</title>
  <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <meta name="description" content="A word counter built in HTML/CSS/JS. Shows number of characters, words, reading time and readability score. Also generates a list of top keywords.">
</head>
<body>
  <div class="container">
    <h1>JS</h1>
    <textarea placeholder="Collez ici..."></textarea>
 
    <div class="right">
    <a href="javascript:window.location.reload()">Réinitialiser JS</a>
    </div>

    <div class="output row">
      <div>DURÉE ► <span id="readingTime">0</span></div>
   
      <div>NOMBRE DE MOTS ► <span id="wordCount">0</span></div>
    </div>
    <div class="output row">
      <div>PHRASES ► <span id="sentenceCount">0</span></div>
      <div>PARAGRAPHES ► <span id="paragraphCount">0</span></div>
    </div>
    <div class="output row">
      <div>CHARACTÈRES ► <span id="characterCount">0</span></div>
      <div id="readability">Show readability score.</div>
    </div>
 
 <label for="pet-select">Type de texte:</label>

  <select name="type" id="type-select">
      <option value="">--Choisir une option--</option>
      <option value="poesie">Poésie</option>
      <option value="blog">Blog</option>
  </select>
    <div>
    <input type="checkbox" id="option10" name="option10"
           checked>
    <label for="option10">+10€</label>
  </div>

  <div>
    <input type="checkbox" id="option20" name="option20">
    <label for="option20">+20€</label>
  </div>
    <div class="keywords">
      Mots les plus utilisés :
      <ul id="topKeywords">
      </ul>
    </div>
    <div class="">
      <span> PRIX :</span><span id="sp_prix"></span>
    </div>
  </div>
  
  
  
  
  
  <script type="text/javascript" src="js/word-counter.js"></script>
  <script type="text/javascript">
    
    input.addEventListener('keyup', function() {
       calculPrix();
    });
    
    function calculPrix(){
       var typeSelect = document.getElementById('type-select');
        valTS = typeSelect.value;
        
        if(valTS == "poesie" ){
           alert('Vous avez choisi poesie');
        }else if(valTS == "blog"){
          alert('Vous avez choisi Blog');
        }else{
          console.log('Aucune option choisie...');
        }
        
        
        //affichage dans la zone prix
        document.getElementById('sp_prix').innerHTML = '100';
    }
  </script>
</body>

</html>

le reste.. ce ne sont que des conditions et des multiplications...
je te laisse chercher.
0
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020 > jordane45 Messages postés 38264 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 31 octobre 2024
27 mars 2020 à 16:02
Merci je le test tout de suite !
Pour le reste, je pourrai te mettre mon code "amateur" que j'aurai testé en retour ?
0
nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020 > nathan2020 Messages postés 9 Date d'inscription vendredi 27 mars 2020 Statut Membre Dernière intervention 27 mars 2020
27 mars 2020 à 16:05
La fenetre alerte me gène si je modifie le texte...elle apparait à chaque fois.
Pour les opérations c'est là que je galère total... :-(
0