Nodejs String Swap swap(a, b)

Here you can find the source of swap(a, b)

Method Source Code

String.prototype.swap = function(a, b) {
    var array = this.split('');
    var tmp = array[a];
    array[a] = array[b];/*ww  w .  j a v a  2s.c om*/
    array[b] = tmp;
    return array.join('');
}

function permutation(str, start) {
    if (start == str.length - 1) {
        console.log(str);
    } else {
        for (var i = start; i < str.length; i++) {
          permutation(str.swap(start, i), start+1);
       }
   }
}

permutation('abc', 0);

Related

  1. swap(l,r)
    var pers=[];
    function permute(s,l,r){
      if(l==r) pers.push(s);
      else {
        for(var i=l;i<=r;i++) {
          s=s.swap(l,i);
          permute(s,l+1,r);
          s=s.swap(l,i);
    String.prototype.swap=function(l,r) {
      return this.split('').map((a,i)=>i==l?this[r]:i==r?this[l]:a).join('');
    permute('abc',0,2);
    console.log(pers);
    
  2. swapLetters(index)
    String.prototype.swapLetters = function(index) {
        var words = this.split("");
        var firstLetter = words[index];
        var lastLetter = words[words.length - 1 - index];
        var temp = firstLetter;
        words[index] = lastLetter;
        words[words.length -1 - index] = temp;
        return words.join("");
    };
    ...
    
  3. swap_chars(i,j)
    String.prototype.swap_chars = function(i,j) {
        var array_string = this.split("");
        tmp = array_string[i];
        array_string[i] = array_string[j];
        array_string[j] = tmp;
        return array_string.join("");
    };
    
  4. swap_substr(i)
    String.prototype.swap_substr = function(i) {
        return this.substr(0, i) + this.substr(i).split("").reverse().join("");
    };