JohnNgo
JohnNgo

Reputation: 53

How do I log some tests for javascript?

I was hoping to get your assistance with this "Is Unique" algorithm in Javascript.

var allUniqueChars = function(string) {

  // O(n^2) approach, no additional data structures used
  // for each character, check remaining characters for duplicates
  for (var i = 0; i < string.length; i++) {
    console.log(i);
    for (var j = i + 1; j < string.length; j++) {
      if (string[i] === string[j]) {
        return false; // if match, return false
      }
    }
  }
  return true; // if no match, return true
};

/* TESTS */
// log some tests here
allUniqueChars('er412344');

I am looking to log some tests, to see it display in the console. How do I call the function with unique strings to test it?

John

Upvotes: 3

Views: 60

Answers (3)

Attersson
Attersson

Reputation: 4866

Run the snippet multiple times to generate unique random strings and display results:

var allUniqueChars = function(string) {
  for (var i = 0; i < string.length; i++)
    for (var j = i + 1; j < string.length; j++)
      if (string[i] === string[j])
        return false;
  return true;
};

var getUniqueStr = () => Math.random().toString(36).substr(2, 9);

let myStringArray = []; 
for(var i =0 ; i<8; i++) // 8 test cases in this example
  myStringArray.push(getUniqueStr());

console.log(myStringArray.map(e=>e + " : " + allUniqueChars(e)));

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 205979

You can always create an Array with your strings and test like:

var allUniqueChars = function(string) {

  // O(n^2) approach, no additional data structures used
  // for each character, check remaining characters for duplicates
  for (var i = 0; i < string.length; i++) {
    for (var j = i + 1; j < string.length; j++) {
      if (string[i] === string[j]) {
        return false; // if match, return false
      }
    }
  }
  return true; // if no match, return true
};

/* TESTS */
// log some tests here

[
'er412344',
'ghtu',
'1234',
'abba'
].forEach(v => console.log(allUniqueChars(v)));

MDN Array.prototype.foreach

Upvotes: 3

jcroskery
jcroskery

Reputation: 155

You can use this function found here to generate random strings for testing (not mine!):

var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

Upvotes: 0

Related Questions