pocket-lodash icon indicating copy to clipboard operation
pocket-lodash copied to clipboard

lodash源码分析之trimEnd

Open HeftyKoo opened this issue 4 years ago • 0 comments

本文为读 lodash 源码的第三百三十九篇,后续文章会更新到这个仓库中,欢迎 star:pocket-lodash

gitbook也会同步仓库的更新,gitbook地址:pocket-lodash

依赖

import castSlice from './.internal/castSlice.js'
import charsEndIndex from './.internal/charsEndIndex.js'
import stringToArray from './.internal/stringToArray.js'

《lodash源码分析之castSlice》

《lodash源码分析之charsEndIndex》

《lodash源码分析之stringToArray》

源码分析

trimEnd 是将字符串 string 后面指定的字符 chars 移除,如果没有指定 chars ,则默认为空格。

源码如下:

const methodName = ''.trimRight ? 'trimRight': 'trimEnd'
function trimEnd(string, chars) {
  if (string && chars === undefined) {
    return string[methodName]()
  }
  if (!string || !chars) {
    return (string || '')
  }
  const strSymbols = stringToArray(string)
  const end = charsEndIndex(strSymbols, stringToArray(chars)) + 1
  return castSlice(strSymbols, 0, end).join('')
}

处理过程基本和 trim 一致,但是不对前面的字符串处理,因此 castSlice 截取的时候,直接从第一个索引位置也即 0 开始截取。

在没有传 chars 的时候,行为和字符串原生的方法 trimEnd 一致,这里做了个兼容,trimRight 只是 trimEnd 的别名。

trim 的分析参考:《lodash源码分析之trim》

License

署名-非商业性使用-禁止演绎 4.0 国际 (CC BY-NC-ND 4.0)

最后,所有文章都会同步发送到微信公众号上,欢迎关注,欢迎提意见:

作者:对角另一面

HeftyKoo avatar May 30 '20 08:05 HeftyKoo