1
6var customSortString = function(S, T) {
7 let r= '';
8 for (let i = 0, l = S.length; i < l; i++) {
9 if(T.includes(S[i])) {
10 r += S[i];
11 T = T.replace(S[i], '');
12 }
13 }
14
15 let rArr = [...r];
16 for (let i = 0, l = T.length; i < l; i++) {
17 let index = rArr.indexOf(T[i]);
18 if(index >= 0) {
19 rArr.splice(index, 0, T[i]);
20 } else {
21 rArr.push(T[i]);
22 }
23 }
24
25 return rArr.join('');
26
27};
28
29ensureEqual(customSortString("cba", "abcd"), "cbad", 'test 1');
30ensureEqual(customSortString("cba", "abcdef"), "cbadef", 'test 2');
31ensureEqual(customSortString("cbafg", "abcd"), "cbad", 'test 3');
32ensureEqual(customSortString("kqep", "pekeq"), "kqeep", 'test 4');