zoukankan      html  css  js  c++  java
  • 漂亮的代码5:数组与字符一样的操作

    看到这题:

    
    // 依次替换第一个参数中的字符串,用第二个参数。
    var str = "TRaduttore"
    
    str.tr( "auioe", "4-103" )  // -> "TR4d-tt0r3"
    str.tr( "aeiouR", ["A","E","I","O","U","r"] )  // -> "TrAdUttOrE"
    
    var hi = "Hello Happy CodeWarriors"
    
    hi.tr( ["ello","Happy","Wa","ior"],["ola","Felices","Gue","ero"]) // -> "Hola Felices CodeGuerreros"
    hi.tr( ["ll","pp","rr"], "LPR" )  // -> "HeLo HaPy CodeWaRiors"
    
    

    这是我解决的方案:

    String.prototype.tr1 = function(fromList, toList) {
        fromList = fromList || [];
        toList = toList || [];
    
        var pairs = {};
    
        var a = Array.isArray(fromList) ? fromList : fromList.split("");
        var b = Array.isArray(toList) ? toList : toList.split("");
    
        a.forEach((x, i) => pairs[x] = b[i]);
    
        return a.reduce((acc, cur) => acc.replace(new RegExp(cur, "g"), function(x) {
            return pairs[x] + "" || ""; // 这里如果 toList 中包括 0 的话就不行,所以加上一个空字符转成字符,在这里卡了很久。
        }), this);
    
    }
    
    

    看别人的解决方案:

    String.prototype.tr = function(from, to) {
        for (var s = this, i = 0; i < from.length; i++) {
            s = s.split(from[i]).join(to ? to[i] : '');
        }
    
        return s;
    }
    
    // 我自己改进一下
    String.prototype.tr = function(from, to) {
        return (Array.isArray(from) ? from : from.split("")).reduce((acc, cur, i) => acc.split(cur).join(to ? to[i] : ''), this);
    }
    
    

    自己写成了一堆屎,好好学习。

  • 相关阅读:
    linux 文件记录锁详解
    Linux fcntl函数详解
    大数相加
    信雅达面试题atoi函数实现
    linux getopt函数详解
    strcpy和memcpy的区别
    手把手写数据结构之栈操作
    手把手写数据结构之队列操作
    手把手写数据结构之双向链表操作
    ORACLE查询内存溢出
  • 原文地址:https://www.cnblogs.com/htoooth/p/5546646.html
Copyright © 2011-2022 走看看