Skip to content

Commit db516ad

Browse files
committed
added answer for ch1_q5
1 parent da4534e commit db516ad

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
module.exports = Strings_1_5 = (function() {
2+
return {
3+
// Checks if a string can converted to another string with a single edit
4+
// Solution #5 from the book.
5+
// @param {String} first - first string
6+
// @param {String} second - second string
7+
// @retuns {Boolean} - true if a string can converted to another string with a single edit
8+
oneAway: function(first, second) {
9+
10+
var skip = true;
11+
var s1 = first.length > second.length ? first : second;
12+
var s2 = first.length > second.length ? second : first;
13+
var diff = s1.length - s2.length;
14+
var i1 = 0,
15+
i2 = 0;
16+
17+
if (diff > 1) {
18+
return false;
19+
}
20+
while (i1 < s2.length) {
21+
var i2 = i1 + (!skip ? diff : 0);
22+
if (s1.charCodeAt(i2) !== s2.charCodeAt(i1)) {
23+
if (skip) {
24+
i1 = i1 - diff;
25+
skip = false;
26+
} else {
27+
return false;
28+
}
29+
}
30+
i1++;
31+
}
32+
return true;
33+
}
34+
};
35+
}());
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
require('../../test_helper');
2+
describe('1.5 #oneAway', function() {
3+
it('returns true if a string can converted to another string with a single edit', function() {
4+
expect(Strings_1_5.oneAway('pale', 'ple')).to.be.true;
5+
expect(Strings_1_5.oneAway('pales', 'pale')).to.be.true;
6+
expect(Strings_1_5.oneAway('pale', 'bale')).to.be.true;
7+
});
8+
it('returns false if a string can not be converted to another string in a single edit', function() {
9+
expect(Strings_1_5.oneAway('pale', 'ble')).to.be.false;
10+
});
11+
});

0 commit comments

Comments
 (0)