Skip to content

Commit

Permalink
Fix commonCharacters.js - add createHash function and add comments wi…
Browse files Browse the repository at this point in the history
…thin commonCharacters function
  • Loading branch information
fay-jai committed Feb 6, 2015
1 parent 3a7e67f commit e193962
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions commonCharacters/commonCharacters.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Write a function `f(a, b)` which takes two strings as arguments and returns a
* string containing only the unique characters found in both strings, in the
* string containing only the unique characters found in both strings, in the
* order that they appeared in `a`. Remember to skip spaces and characters you
* have already encountered!
*
Expand All @@ -10,7 +10,6 @@
* Extra credit: Extend your function to handle more than two input strings.
*/


var commonCharacters = function () {
var args = Array.prototype.slice.call(arguments);
if (args.length < 2) throw new Error('Require at least 2 input strings');
Expand All @@ -22,9 +21,16 @@ var commonCharacters = function () {
* Key step here: keep on reducing the unique set until you get the result across
* all strings
*/

/*
* The reason createHash(first) is needed is because in order to maintain a
* unique set after each reduction, you'll need to pass an initial object with
* with the characters so far. If an empty object is passed, then of course there
* are no other characters that will match against the empty object.
*/
var result = args.reduce(function (acc, cur) {
return createUniqueSet(acc, cur);
});
}, createHash(first));

for (var i = 0; i < first.length; i += 1) {
if (result[first[i]]) {
Expand All @@ -36,13 +42,23 @@ var commonCharacters = function () {
return str;
};

var createUniqueSet = function (a, b) {
var hashB = {};
var createHash = function (string) {
var result = {};
for (var i = 0; i < string.length; i += 1) {
result[ string[i] ] = true;
}
return result;
};

var createUniqueSet = function (obj, string) {
var result = {};
var len = string.length;
var i;

for (i = 0; i < b.length; i += 1) {
result[b[i]] = true;
for (i = 0; i < len; i += 1) {
if (obj[ string[i] ]) {
result[ string[i] ] = true;
}
}

return result;
Expand Down

0 comments on commit e193962

Please sign in to comment.