Source
Girl Develop It San Francisco,
Teaching Materials,
Exercises: Strings: MixUp
Description
Given two strings s1 and s2 and an integer n, swap the first n
characters of s1 and s2 and concatenate the results, separated by
a space. If either string is less than or equal to n characters in
length, return them unmodified but concatenated, separated by a space.
| 1
2
 | 'foo', 'bar', 3 ⟹ 'foo bar'
'foobar', 'bazqux', 3 ⟹ 'bazbar fooqux'
 | 
My solution
| 1
2
3
4
5
6
7
8
 | const headswap = (s1, s2, n) =>
  s1.length <= n || s2.length <= n
      ? s1 + ' ' + s2
      : s2.substring(0, n) + s1.substring(n) + ' ' +
        s1.substring(0, n) + s2.substring(n);
module.exports = headswap;
 | 
Tests
| 1
2
3
4
5
6
7
8
9
10
11
12
 | const assert = require('assert')
    , headswap = require('./headswap.js');
describe('#headswap()', () => {
    it('Should leave strings unmodified', () => {
        assert.strictEqual(headswap('foo', 'bar', 3), 'foo bar');
    });
    it('Should modify strings', () => {
        assert.strictEqual(headswap('foobar', 'bazqux', 3), 'bazbar fooqux');
    });
});
 |