Skip to content

Commit

Permalink
Add normalized distances to all results
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Nov 8, 2014
1 parent 99a9b62 commit 7dde286
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions lib/franc.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,36 @@ function getTopScript(value, scripts) {
return [topScript, topCount];
}

/**
* Normalize the difference for each tuple in
* `distances`.
*
* @param {string} value
* @param {Array.<Array.<string, number>>} distances
* @return {Array.<Array.<string, number>>} - Normalized
* distances.
*/

function normalize(value, distances) {
var max,
min,
index,
length;

min = distances[0][1];

max = (value.length * MAX_DIFFERENCE) - min;

index = -1;
length = distances.length;

while (++index < length) {
distances[index][1] = 1 - ((distances[index][1] - min) / max);
}

return distances;
}

/**
* Create a single tuple as a list of tuples from a given
* language code.
Expand All @@ -276,7 +306,6 @@ function singleLanguageTuples(language) {

function detectAll(value, options) {
var script;
options = options || {};

if (!value || value.length < MIN_LENGTH) {
return singleLanguageTuples('und');
Expand All @@ -300,10 +329,13 @@ function detectAll(value, options) {
}

/**
* Get all distances for a given script.
* Get all distances for a given script, and
* normalize the distance values.
*/

return getDistances(utilities.asTuples(value), data[script[0]], options);
return normalize(value, getDistances(
utilities.asTuples(value), data[script[0]], options || {}
));
}

/**
Expand All @@ -318,13 +350,13 @@ function detect(value, options) {
}

/**
* Expose `detectAll` on `franc`.
* Expose `detectAll` on `detect`.
*/

detect.all = detectAll;

/**
* Expose `franc`.
* Expose `detect`.
*/

module.exports = detect;

0 comments on commit 7dde286

Please sign in to comment.