-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotateString.js
More file actions
38 lines (30 loc) · 1000 Bytes
/
rotateString.js
File metadata and controls
38 lines (30 loc) · 1000 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Given a string and an offset, rotate string by offset. routate from left to right.
// Given 'abcdefg'
// offset=0 => 'abcdefg'
// offset=1 => 'gabcdef'
// offset=2 => 'fgabcde'
// offset=3 => 'efgabcd'
const rotateStr = (str, offset) => {
if (typeof offset !== 'number' || offset < 0) throw Error('invalid offset')
if (offset > str.length) offset = offset % str.length
const headStr = str.slice(str.length - offset)
const rareStr = str.slice(0, str.length - offset)
return headStr.concat(rareStr)
}
console.log(rotateStr('abcdefg', 3))
console.log(rotateStr('abc', 7))
/*
substr()
* 第一个参数 起始位置 前闭
* 当第一个参数为负,与 length 相加
* 第二个参数 截取的个数
* 第二个参数为负,将其转为 0
substring()
* 两个参数 前闭后开
* 当第二个参数空缺,切到尾
* 当参数为负,将其转为 0
slice()
* 两个参数 前闭后开
* 当第二个参数空缺,切到尾
* 当参数为负,与 length 相加
*/