Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

padStart 的 polyfill #33

Open
zwhu opened this issue Feb 5, 2017 · 1 comment
Open

padStart 的 polyfill #33

zwhu opened this issue Feb 5, 2017 · 1 comment

Comments

@zwhu
Copy link
Owner

zwhu commented Feb 5, 2017

🤔

今天在看 ES7 新增的部分 Api 的时候刚好看到 padStart 的这个方法,好像还挺实用的,而且也想在正式开始工作之前先找找写代码的感觉,于是顺手(其实还是花了不少时间的)就实现了这个 polyfill。

相关的 API 用法在 MDN 上有说明。 链接 下面是具体实现

if(!String.prototype.padStart)
    String.prototype.padStart = 
       // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
        function (maxLength, fillString=' ') {
            if(Object.prototype.toString.call(fillString) !== "[object String]") throw new TypeError('fillString must be String')
            let str = this
            // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
            if(str.length >= maxLength) return String(str)

            let fillLength = maxLength - str.length, 
 				times = Math.ceil(fillLength / fillString.length)
           
           // 这个算法叫啥?
           // SICP 的中文版第 30页 有用到同种算法计算乘幂计算
            while(times >>= 1) { 
                fillString += fillString
                    if(times === 1){
                       fillString += fillString
                    }     
            }
            return fillString.slice(0, fillLength) + str  
        }
// padStart  对于我来说最常用的地方就在于时间或者数字格式补全了

'5'.padStart(2, '0') // '05'
'15'.padStart(2, '0') // '15'

ps:
写完之后突然发现这个好像就是之前 npm 的 left-pad 删库事件;隐约记得好多人都重写过这个库。anyway, 练手的目的算是达到了。

@yutingzhao1991
Copy link

npm 上有一个包 https://www.npmjs.com/package/left-pad 。我记得之前还出过一次事故,这个包下线了还是怎么着把react搞挂了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants