Compare length of two strings: Difference between revisions

Content added Content deleted
Line 335: Line 335:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang JavaScript>// file stringlensort.js
<lang JavaScript>// file stringlensort.js

/**
* Compare and report strings lengths.
*
* @param {Element} input - a TextArea DOM element with input
* @param {Element} output - a TextArea DOM element for output
*/
function compareStringsLength(input, output) {
function compareStringsLength(input, output) {

// Safe defaults.
//
output.value = "";
output.value = "";
let output_lines = [];
let output_lines = [];

// Split input into an array of lines.
//
let strings = input.value.split(/\r\n|\r|\n/g);
let strings = input.value.split(/\r\n|\r|\n/g);

// Is strings array empty?
//
if (strings && strings.length > 0) {
if (strings && strings.length > 0) {

// Remove leading and trailing spaces.
//
for (let i = 0; i < strings.length; i++)
for (let i = 0; i < strings.length; i++)
strings[i] = strings[i].trim();
strings[i] = strings[i].trim();

// Sort by lengths.
//
strings.sort((a, b) => a.length - b.length);
strings.sort((a, b) => a.length - b.length);

// Remove empty strings.
//
while (strings[0] == "")
while (strings[0] == "")
strings.shift();
strings.shift();

// Check if any strings remain.
//
if (strings && strings.length > 0) {
if (strings && strings.length > 0) {

// Get min and max lengths of strings.
//
const min = strings[0].length;
const min = strings[0].length;
const max = strings[strings.length - 1].length;
const max = strings[strings.length - 1].length;

// Build output verses - longest strings first.
//
for (let i = strings.length - 1; i >= 0; i--) {
for (let i = strings.length - 1; i >= 0; i--) {
let length = strings[i].length;
let length = strings[i].length;
Line 360: Line 394:
output_lines.push(`"${strings[i]}" has length ${length} and ${predicate}\n`);
output_lines.push(`"${strings[i]}" has length ${length} and ${predicate}\n`);
}
}

// Send all lines from output_lines array to an TextArea control.
//
output.value = output_lines.join('');
output.value = output_lines.join('');
}
}
Line 366: Line 403:


document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output);</lang>
compareStringsLength(input, output);
</lang>
<lang html><html>
<lang html><html>