forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArbitraryBase.js
More file actions
Latest commit
50 lines (46 loc) · 1.81 KB
/
Copy pathArbitraryBase.js
File metadata and controls
50 lines (46 loc) · 1.81 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Converts a string from one base to other
* @param {string} stringInBaseOne String in input base
* @param {string} baseOneCharacters Character set for the input base
* @param {string} baseTwoCharacters Character set for the output base
* @returns {string}
*/
constconvertArbitraryBase=(stringInBaseOne,baseOneCharacters,baseTwoCharacters)=>{
if([stringInBaseOne,baseOneCharacters,baseTwoCharacters].map(arg=>typeofarg).some(type=>type!=='string')){
thrownewTypeError('Only string arguments are allowed')
}
[baseOneCharacters,baseTwoCharacters].forEach(baseString=>{
constcharactersInBase=[...baseString]
if(charactersInBase.length!==newSet(charactersInBase).size){
thrownewTypeError('Duplicate characters in character set are not allowed')
}
})
constreversedStringOneChars=[...stringInBaseOne].reverse()
conststringOneBase=baseOneCharacters.length
letvalue=0
letplaceValue=1
for(constdigitofreversedStringOneChars){
constdigitNumber=baseOneCharacters.indexOf(digit)
if(digitNumber===-1){
thrownewTypeError(`Not a valid character: ${digit}`)
}
value+=(digitNumber*placeValue)
placeValue*=stringOneBase
}
letstringInBaseTwo=''
conststringTwoBase=baseTwoCharacters.length
while(value>0){
constremainder=value%stringTwoBase
stringInBaseTwo=baseTwoCharacters.charAt(remainder)+stringInBaseTwo
value/=stringTwoBase
}
constbaseTwoZero=baseTwoCharacters.charAt(0)
returnstringInBaseTwo.replace(newRegExp(`^${baseTwoZero}+`),'')
}
export{convertArbitraryBase}
// > convertArbitraryBase('98', '0123456789', '01234567')
// '142'
// > convertArbitraryBase('98', '0123456789', 'abcdefgh')
// 'bec'
// > convertArbitraryBase('129', '0123456789', '01234567')
// '201'