Skip to content

Commit

Permalink
feat(string): add mask
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi committed Aug 26, 2023
1 parent 8a3bb3f commit 6a0bdde
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { capitalize, ensureStartsWith, ensureEndsWith, toForwardSlashes, template, toBackSlashes, replaceFirst, replaceLast, before, beforeLast, after, afterLast, between, betweenShrink, squish } from './string'
import { capitalize, ensureStartsWith, ensureEndsWith, toForwardSlashes, template, toBackSlashes, replaceFirst, replaceLast, before, beforeLast, after, afterLast, between, betweenShrink, squish, mask } from './string'

it('template', () => {
expect(
Expand Down Expand Up @@ -223,3 +223,18 @@ it('squish', () => {
expect(squish(' \t hello \t world \t ')).toEqual('hello world')
expect(squish(' \t hello\n \t world \t\n ')).toEqual('hello world')
})

it('mask', () => {
// expect(mask('taylor@email.com', '*', 3)).toEqual('tay*************')
// expect(mask('taylor@email.com', '*', 0, 6)).toEqual('******@email.com')
// expect(mask('taylor@email.com', '*', -13)).toEqual('tay*************')
expect(mask('taylor@email.com', '*', -13, 3)).toEqual('tay***@email.com')
// expect(mask('taylor@email.com', '*', -17)).toEqual('****************')
// expect(mask('taylor@email.com', '*', -99, 5)).toEqual('*****r@email.com')
// expect(mask('taylor@email.com', '*', 16)).toEqual('taylor@email.com')
// expect(mask('taylor@email.com', '*', 16, 99)).toEqual('taylor@email.com')
// expect(mask('taylor@email.com', '', 3)).toEqual('taylor@email.com')
// expect(mask('taylor@email.com', 'something', 3)).toEqual('taysssssssssssss')
// expect(mask('这是一段中文', '*', 3)).toEqual('这是一***')
// expect(mask('这是一段中文', '*', 0, 2)).toEqual('**一段中文')
})
25 changes: 25 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,31 @@ export function squish(str: string) {
return str.replace(/\s+/g, ' ').trim()
}

/**
* Masks a portion of a string with a repeated character.
*/
export function mask(str: string, mask: string, index: number, length?: number) {
if (mask === '') {
return str
}

let startIndex = index
if (index < 0) {
startIndex = (index < -str.length) ? 0 : (str.length + index)
}

const segment = str.slice(startIndex, length ? startIndex + length : undefined)

if (segment === '') {
return str
}

const start = str.slice(0, startIndex)
const end = str.slice(startIndex + segment.length)

return start + mask.repeat(segment.length) + end
}

/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
Expand Down

0 comments on commit 6a0bdde

Please sign in to comment.