算法与转换:Part1
# 字符串基数转换
/**
* 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}
*/
const convertArbitraryBase = (stringInBaseOne, baseOneCharacters, baseTwoCharacters) => {
if ([stringInBaseOne, baseOneCharacters, baseTwoCharacters].map(arg => typeof arg).some(type => type !== 'string')) {
throw new TypeError('Only string arguments are allowed')
}
[baseOneCharacters, baseTwoCharacters].forEach(baseString => {
const charactersInBase = [...baseString]
if (charactersInBase.length !== new Set(charactersInBase).size) {
throw new TypeError('Duplicate characters in character set are not allowed')
}
})
const reversedStringOneChars = [...stringInBaseOne].reverse()
const stringOneBase = baseOneCharacters.length
let value = 0
let placeValue = 1
for (const digit of reversedStringOneChars) {
const digitNumber = baseOneCharacters.indexOf(digit)
if (digitNumber === -1) {
throw new TypeError(`Not a valid character: ${digit}`)
}
value += (digitNumber * placeValue)
placeValue *= stringOneBase
}
let stringInBaseTwo = ''
const stringTwoBase = baseTwoCharacters.length
while (value > 0) {
const remainder = value % stringTwoBase
stringInBaseTwo = baseTwoCharacters.charAt(remainder) + stringInBaseTwo
value /= stringTwoBase
}
const baseTwoZero = baseTwoCharacters.charAt(0)
return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`), '')
}
// > convertArbitraryBase('98', '0123456789', '01234567')
// '142'
// > convertArbitraryBase('98', '0123456789', 'abcdefgh')
// 'bec'
// > convertArbitraryBase('129', '0123456789', '01234567')
// '201'
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
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
# Buffer 转 Base64
// About base64: https://en.wikipedia.org/wiki/Base64
/**
* Converts an array of bytes to base64 encoding
* @param {ArrayBuffer} binaryData An ArrayBuffer which represents an array of bytes
* @returns {string} A string containing the base64 encoding of `binaryData`
*/
function bufferToBase64 (binaryData) {
// The base64 encoding uses the following set of characters to encode any binary data as text
const base64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
// Every 3 bytes translates to 4 base64 characters, if we have less than 3 bytes we must append '=' chars as padding
const padding = 3 - (binaryData.byteLength % 3)
// Create an instance of Uint8Array, to read from the binaryData array buffer
const byteView = new Uint8Array(binaryData)
let result = ''
// Loop through all bytes in the buffer, in increments of 3 bytes
for (let i = 0; i < byteView.byteLength; i += 3) {
// Get the index for the next 4 base64 chars
const char1 = (byteView[i] & 252) >> 2
const char2 = ((byteView[i] & 3) << 4) + ((byteView[i + 1] & 240) >> 4)
const char3 = ((byteView[i + 1] & 15) << 2) + ((byteView[i + 2] & 192) >> 6)
const char4 = byteView[i + 2] & 63
result +=
base64Table[char1] +
base64Table[char2] +
base64Table[char3] +
base64Table[char4]
}
// Add padding '=' chars if needed
if (padding !== 3) {
const paddedResult = result.slice(0, result.length - padding) + '='.repeat(padding)
return paddedResult
}
return result
}
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
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
# Base64 转 Buffer
// About base64: https://en.wikipedia.org/wiki/Base64
/**
* Converts a base64 string to an array of bytes
* @param {string} b64 A base64 string
* @returns {ArrayBuffer} An ArrayBuffer representing the bytes encoded by the base64 string
*/
function base64ToBuffer (b64) {
// The base64 encoding uses the following set of characters to encode any binary data as text
const base64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
// Find the index of char '=' first occurrence
const paddingIdx = b64.indexOf('=')
// Remove padding chars from base64 string, if there are any
const b64NoPadding = paddingIdx !== -1 ? b64.slice(0, paddingIdx) : b64
// Calculate the length of the result buffer
const bufferLength = Math.floor((b64NoPadding.length * 6) / 8)
// Create the result buffer
const result = new ArrayBuffer(bufferLength)
// Create an instance of Uint8Array, to write to the `result` buffer
const byteView = new Uint8Array(result)
// Loop through all chars in the base64 string, in increments of 4 chars, and in increments of 3 bytes
for (let i = 0, j = 0; i < b64NoPadding.length; i += 4, j += 3) {
// Get the index of the next 4 base64 chars
const b64Char1 = base64Table.indexOf(b64NoPadding[i])
const b64Char2 = base64Table.indexOf(b64NoPadding[i + 1])
let b64Char3 = base64Table.indexOf(b64NoPadding[i + 2])
let b64Char4 = base64Table.indexOf(b64NoPadding[i + 3])
// If base64 chars 3 and 4 don't exit, then set them to 0
if (b64Char3 === -1) b64Char3 = 0
if (b64Char4 === -1) b64Char4 = 0
// Calculate the next 3 bytes
const byte1 = (b64Char1 << 2) + ((b64Char2 & 48) >> 4)
const byte2 = ((b64Char2 & 15) << 4) + ((b64Char3 & 60) >> 2)
const byte3 = ((b64Char3 & 3) << 6) + b64Char4
byteView[j] = byte1
byteView[j + 1] = byte2
byteView[j + 2] = byte3
}
return result
}
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
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
# 二进制转十进制
function binaryToDecimal (binaryString) {
let decimalNumber = 0
const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits
binaryDigits.forEach((binaryDigit, index) => {
decimalNumber += binaryDigit * (Math.pow(2, index)) // Summation of all the decimal converted digits
})
return decimalNumber
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 十进制转二进制
function decimalToBinary (num) {
const bin = []
while (num > 0) {
bin.unshift(num % 2)
num >>= 1 // basically /= 2 without remainder if any
}
return bin.join('')
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 二进制转十六进制
const pad = (num, padlen) => {
const pad = new Array(1 + padlen).join(0)
return (pad + num).slice(-pad.length)
}
const hexLookup = (bin) => {
let binary = bin
if (binary.length < 4) {
binary = pad(binary, 4)
}
switch (binary) {
case '0000': return '0'
case '0001': return '1'
case '0010': return '2'
case '0011': return '3'
case '0100': return '4'
case '0101': return '5'
case '0110': return '6'
case '0111': return '7'
case '1000': return '8'
case '1001': return '9'
case '1010': return 'A'
case '1011': return 'B'
case '1100': return 'C'
case '1101': return 'D'
case '1110': return 'E'
case '1111': return 'F'
}
}
const binaryToHex = (binaryString) => {
/*
Function for convertung Binary to Hex
1. The conversion will start from Least Significant Digit (LSB) to the Most Significant Bit (MSB).
2. We divide the bits into sections of 4-bits starting from LSB to MSB.
3. If the MSB get less than 4 bits, then we pad 0s to the front of it.
For Example:
Binary String = '1001101'
1. Divide it to 2 parts => ['100', '1101']
2. Pad 0s the MSB so it'll be => ['0100', '1101']
3. Use the lookup table and merge them, therefore the result is 4D.
*/
let result = ''
binaryString = binaryString.split('')
for (let i = binaryString.length - 1; i >= 0; i = i - 4) {
if (i >= 3) {
result += hexLookup(binaryString.slice(i - 3, i + 1).join(''))
} else {
result += hexLookup(binaryString.slice(0, i + 1).join(''))
}
}
return result.split('').reverse().join('')
}
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
51
52
53
54
55
56
57
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
51
52
53
54
55
56
57
# 十六进制转二进制
const binLookup = (key) => ({
0: '0000',
1: '0001',
2: '0010',
3: '0011',
4: '0100',
5: '0101',
6: '0110',
7: '0111',
8: '1000',
9: '1001',
a: '1010',
b: '1011',
c: '1100',
d: '1101',
e: '1110',
f: '1111'
}[key.toLowerCase()]) // select the binary number by valid hex key with the help javascript object
const hexToBinary = (hexString) => {
if (typeof hexString !== 'string') {
throw new TypeError('Argument is not a string type')
}
if (/[^\da-f]/gi.test(hexString)) {
throw new Error('Argument is not a valid HEX code!')
}
/*
Function for converting Hex to Binary
1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table
*/
return hexString.replace(
/[0-9a-f]/gi,
lexeme => binLookup(lexeme)
)
}
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
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
# 十进制转十六进制
function intToHex (num) {
switch (num) {
case 10: return 'A'
case 11: return 'B'
case 12: return 'C'
case 13: return 'D'
case 14: return 'E'
case 15: return 'F'
}
return num
}
function decimalToHex (num) {
const hexOut = []
while (num > 15) {
hexOut.unshift(intToHex(num % 16))
num = Math.floor(num / 16)
}
return intToHex(num) + hexOut.join('')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 十六进制转十进制
function hexToInt (hexNum) {
const numArr = hexNum.split('') // converts number to array
return numArr.map((item, index) => {
switch (item) {
case 'A': return 10
case 'B': return 11
case 'C': return 12
case 'D': return 13
case 'E': return 14
case 'F': return 15
default: return parseInt(item)
}
})
}
function hexToDecimal (hexNum) {
const intItemsArr = hexToInt(hexNum)
return intItemsArr.reduce((accumulator, current, index) => {
return accumulator + (current * Math.pow(16, (intItemsArr.length - (1 + index))))
}, 0)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 十进制转八进制
function decimalToOctal (num) {
let oct = 0
let c = 0
while (num > 0) {
const r = num % 8
oct = oct + (r * Math.pow(10, c++))
num = Math.floor(num / 8) // basically /= 8 without remainder if any
}
return oct
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 八进制转十进制
function octalToDecimal (num) {
let dec = 0
let base = 1
while (num > 0) {
const r = num % 10
num = Math.floor(num / 10)
dec = dec + (r * base)
base = base * 8
}
return dec
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 十进制转罗马数字
/*
Decimal To Roman
This algorithm take decimal number and convert to roman numeral according to standard form (https://en.wikipedia.org/wiki/Roman_numerals#Description)
Algorithm & Explanation : https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html
*/
const values = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
}
const orders = [
'M',
'CM',
'D',
'CD',
'C',
'XC',
'L',
'XL',
'X',
'IX',
'V',
'IV',
'I'
]
function decimalToRoman (num) {
let roman = ''
for (const symbol of orders) {
while (num >= values[symbol]) {
roman += symbol
num -= values[symbol]
}
}
return roman
}
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
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
# 罗马数字转十进制
const values = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
function romanToDecimal (romanNumber) {
let prev = ' '
let sum = 0
let newPrev = 0
for (let i = romanNumber.length - 1; i >= 0; i--) {
const c = romanNumber.charAt(i)
if (prev !== ' ') {
newPrev = values[prev] > newPrev ? values[prev] : newPrev
}
const currentNum = values[c]
if (currentNum >= newPrev) {
sum += currentNum
} else {
sum -= currentNum
}
prev = c
}
return sum
}
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
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
# 颜色:十六进制和 RGB 相互转化
function hexStringToRGB (hexString) {
let r = hexString.substring(0, 2)
let g = hexString.substring(2, 4)
let b = hexString.substring(4, 6)
r = parseInt(r, 16)
g = parseInt(g, 16)
b = parseInt(b, 16)
const obj = { r, g, b }
return obj
}
function RGBToHex (r, g, b) {
if (
typeof r !== 'number' ||
typeof g !== 'number' ||
typeof b !== 'number'
) {
throw new TypeError('argument is not a Number')
}
const toHex = n => (n || '0').toString(16).padStart(2, '0')
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
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
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
# 颜色:HSV 和 RGB 相互转化
/*
* The RGB color model is an additive color model in which red, green, and blue light are added
* together in various ways to reproduce a broad array of colors. The name of the model comes from
* the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV
* representation models how colors appear under light. In it, colors are represented using three
* components: hue, saturation and (brightness-)value. This file provides functions for converting
* colors from one representation to the other. (description adapted from
* https://en.wikipedia.org/wiki/RGB_color_model and https://en.wikipedia.org/wiki/HSL_and_HSV).
*/
/**
* Conversion from the HSV-representation to the RGB-representation.
*
* @param hue Hue of the color.
* @param saturation Saturation of the color.
* @param value Brightness-value of the color.
* @return The tuple of RGB-components.
*/
function hsvToRgb (hue, saturation, value) {
if (hue < 0 || hue > 360) {
throw new Error('hue should be between 0 and 360')
}
if (saturation < 0 || saturation > 1) {
throw new Error('saturation should be between 0 and 1')
}
if (value < 0 || value > 1) {
throw new Error('value should be between 0 and 1')
}
const chroma = value * saturation
const hueSection = hue / 60
const secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1))
const matchValue = value - chroma
return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent)
}
/**
* Conversion from the RGB-representation to the HSV-representation.
*
* @param red Red-component of the color.
* @param green Green-component of the color.
* @param blue Blue-component of the color.
* @return The tuple of HSV-components.
*/
function rgbToHsv (red, green, blue) {
if (red < 0 || red > 255) {
throw new Error('red should be between 0 and 255')
}
if (green < 0 || green > 255) {
throw new Error('green should be between 0 and 255')
}
if (blue < 0 || blue > 255) {
throw new Error('blue should be between 0 and 255')
}
const dRed = red / 255
const dGreen = green / 255
const dBlue = blue / 255
const value = Math.max(Math.max(dRed, dGreen), dBlue)
const chroma = value - Math.min(Math.min(dRed, dGreen), dBlue)
const saturation = value === 0 ? 0 : chroma / value
let hue
if (chroma === 0) {
hue = 0
} else if (value === dRed) {
hue = 60 * ((dGreen - dBlue) / chroma)
} else if (value === dGreen) {
hue = 60 * (2 + (dBlue - dRed) / chroma)
} else {
hue = 60 * (4 + (dRed - dGreen) / chroma)
}
hue = (hue + 360) % 360
return [hue, saturation, value]
}
export function approximatelyEqualHsv (hsv1, hsv2) {
const bHue = Math.abs(hsv1[0] - hsv2[0]) < 0.2
const bSaturation = Math.abs(hsv1[1] - hsv2[1]) < 0.002
const bValue = Math.abs(hsv1[2] - hsv2[2]) < 0.002
return bHue && bSaturation && bValue
}
function getRgbBySection (hueSection, chroma, matchValue, secondLargestComponent) {
function convertToInt (input) {
return Math.round(255 * input)
}
let red
let green
let blue
if (hueSection >= 0 && hueSection <= 1) {
red = convertToInt(chroma + matchValue)
green = convertToInt(secondLargestComponent + matchValue)
blue = convertToInt(matchValue)
} else if (hueSection > 1 && hueSection <= 2) {
red = convertToInt(secondLargestComponent + matchValue)
green = convertToInt(chroma + matchValue)
blue = convertToInt(matchValue)
} else if (hueSection > 2 && hueSection <= 3) {
red = convertToInt(matchValue)
green = convertToInt(chroma + matchValue)
blue = convertToInt(secondLargestComponent + matchValue)
} else if (hueSection > 3 && hueSection <= 4) {
red = convertToInt(matchValue)
green = convertToInt(secondLargestComponent + matchValue)
blue = convertToInt(chroma + matchValue)
} else if (hueSection > 4 && hueSection <= 5) {
red = convertToInt(secondLargestComponent + matchValue)
green = convertToInt(matchValue)
blue = convertToInt(chroma + matchValue)
} else {
red = convertToInt(chroma + matchValue)
green = convertToInt(matchValue)
blue = convertToInt(secondLargestComponent + matchValue)
}
return [red, green, blue]
}
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# 任意字符串转大写或者小写
/*
Explanation :- a user gives a String (it can be incomplete uppercase or
partial uppercase) and then the program would convert it into a
complete(all characters in lower case) lower case string. The
logic we have used in the following program is: All the upper case
characters (A-Z) has ASCII value ranging from 65 to 90 and their
corresponding lower case characters (a-z) have ASCII values 32
greater than them. For example ‘A‘ has an ASCII value of 65
and ‘a‘ has an ASCII value of 97 (65+32). The same applies to other
characters.
*/
/**
* LowerCaseConversion takes any case-style string and converts it to the lower case-style string.
* @param {String} inputString any case style string
* @returns {String} lower case string
*/
const LowerCaseConversion = (inputString) => {
// Take a string and split it into characters.
const newString = inputString.split('').map(char => {
// Get a character code by the use charCodeAt method.
const presentCharCode = char.charCodeAt()
// If the character code lies between 65 to 90 it means they are in the upper case so convert it.
if (presentCharCode >= 65 && presentCharCode <= 90) {
// Convert the case by use of the above explanation.
return String.fromCharCode(presentCharCode + 32)
}
// Else return the characters without any modification.
return char
})
// After modification, with the help of the join method, join all the characters and return them.
return newString.join('')
}
/*
Explanation :- A user gives a string (it can be incomplete lowercase or
partially in lowercase) and then the program converts it into a
completely (all characters in uppercase) uppercase string. The
logic we have used in the following program is: All the lowercase
characters (a-z) has [ASCII](https://en.wikipedia.org/wiki/ASCII) value ranging from 97 to 122 and their
corresponding uppercase characters (A-Z) have ASCII values 32
lesser than them. For example ‘a‘ has an ASCII value of 97
and ‘A‘ has an ASCII value of 65 (97 - 32). The same applies to other
characters.
*/
/**
* upperCaseConversion takes any case-style string and converts it to the uppercase-style string.
* @param {string} inputString Any case style string
* @returns {string} Uppercase string
*/
const upperCaseConversion = (inputString) => {
// Take a string and split it into characters.
const newString = inputString.split('').map(char => {
// Get a character code by the use charCodeAt method.
const presentCharCode = char.charCodeAt()
// If the character code lies between 97 to 122, it means they are in the lowercase so convert it.
if (presentCharCode >= 97 && presentCharCode <= 122) {
// Convert the case by use of the above explanation.
return String.fromCharCode(presentCharCode - 32)
}
// Else return the characters without any modification.
return char
})
// After modification, with the help of the join method, join all the characters and return them.
return newString.join('')
}
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 英尺和米的转换
// Foot: https://en.wikipedia.org/wiki/Foot_(unit)
const feetToMeter = (feet) => {
return feet * 0.3048
}
const meterToFeet = (meter) => {
return meter / 0.3048
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 标准格式时间转 railway 格式时间
/*
The time conversion of normalized time to the railway is a simple algorithm
because we know that if the time is in 'AM' value it means they only want
some changes on hours and minutes and if the time in 'PM' it means the only
want some changes in hour value.
Input Format -> 07:05:45PM
Output Format -> 19:05:45
Problem & Explanation Source : https://www.mathsisfun.com/time.html
*/
/**
* RailwayTimeConversion method converts normalized time string to Railway time string.
* @param {String} timeString Normalized time string.
* @returns {String} Railway time string.
*/
const RailwayTimeConversion = (timeString) => {
// firstly, check that input is a string or not.
if (typeof timeString !== 'string') {
return new TypeError('Argument is not a string.')
}
// split the string by ':' character.
const [hour, minute, scondWithShift] = timeString.split(':')
// split second and shift value.
const [second, shift] = [scondWithShift.substr(0, 2), scondWithShift.substr(2)]
// convert shifted time to not-shift time(Railway time) by using the above explanation.
if (shift === 'PM') {
if (parseInt(hour) === 12) { return `${hour}:${minute}:${second}` } else { return `${parseInt(hour) + 12}:${minute}:${second}` }
} else {
if (parseInt(hour) === 12) { return `00:${minute}:${second}` } else { return `${hour}:${minute}:${second}` }
}
}
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
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
# 温度计量相互转换
// This files has functions to convert different temperature units
// Functions take temperature value as a argument and returns corresponding converted value
const celsiusToFahrenheit = (celsius) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
return Math.round(((celsius) * 9 / 5) + 32)
}
const celsiusToKelvin = (celsius) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
return Math.round((celsius) + 273.15)
}
const celsiusToRankine = (celsius) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
return Math.round(((celsius) * 9 / 5) + 491.67)
}
const fahrenheitToCelsius = (fahrenheit) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
return Math.round(((fahrenheit) - 32) * 5 / 9)
}
const fahrenheitToKelvin = (fahrenheit) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
return Math.round((((fahrenheit) - 32) * 5 / 9) + 273.15)
}
const fahrenheitToRankine = (fahrenheit) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
return Math.round((fahrenheit) + 459.67)
}
const kelvinToCelsius = (kelvin) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
return Math.round((kelvin) - 273.15)
}
const kelvinToFahrenheit = (kelvin) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
return Math.round((((kelvin) - 273.15) * 9 / 5) + 32)
}
const kelvinToRankine = (kelvin) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
return Math.round(((kelvin) * 9 / 5))
}
const rankineToCelsius = (rankine) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
// Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
return Math.round(((rankine) - 491.67) * 5 / 9)
}
const rankineToFahrenheit = (rankine) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
// Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
return Math.round((rankine) - 459.67)
}
const rankineToKelvin = (rankine) => {
// Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
// Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
return Math.round(((rankine) * 5 / 9))
}
const reaumurToKelvin = (reaumur) => {
// Reference:- http://www.csgnetwork.com/temp2conv.html
return Math.round(((reaumur) * 1.25 + 273.15))
}
const reaumurToFahrenheit = (reaumur) => {
// Reference:- http://www.csgnetwork.com/temp2conv.html
return Math.round(((reaumur) * 2.25 + 32))
}
const reaumurToCelsius = (reaumur) => {
// Reference:- http://www.csgnetwork.com/temp2conv.html
return Math.round(((reaumur) * 1.25))
}
const reaumurToRankine = (reaumur) => {
// Reference:- http://www.csgnetwork.com/temp2conv.html
return Math.round(((reaumur) * 2.25 + 32 + 459.67))
}
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# 字符串转 Title Case
/*
Problem statement and Explanation : https://www.codeproject.com/Tips/162540/Letter-Case-Conversion-Algorithms-Title-Case-Toggl.
[Title case](https://en.wikipedia.org/wiki/Title_case) is a style where all words are capitalized. Officially, title case
does not capitalize some words, such as very short words like "a" or "is", but for the purposes of this function, a general approach
is taken where all words are capitalized regardless of length.
*/
/**
* The titleCaseConversion function converts a string into a title case string.
* @param {string} inputString The input string which can have any types of letter casing.
* @returns {string} A string that is in title case.
*/
const titleCaseConversion = (inputString) => {
if (inputString === '') return ''
// Extract all space separated string.
const stringCollections = inputString.split(' ').map(word => {
let firstChar = ''
// Get the [ASCII](https://en.wikipedia.org/wiki/ASCII) character code by the use charCodeAt method.
const firstCharCode = word[0].charCodeAt()
// If the ASCII character code lies between 97 to 122 it means they are in the lowercase so convert it.
if (firstCharCode >= 97 && firstCharCode <= 122) {
// Convert the case by use of the above explanation.
firstChar += String.fromCharCode(firstCharCode - 32)
} else {
// Else store the characters without any modification.
firstChar += word[0]
}
const newWordChar = word.slice(1).split('').map(char => {
// Get the ASCII character code by the use charCodeAt method.
const presentCharCode = char.charCodeAt()
// If the ASCII character code lies between 65 to 90, it means they are in the uppercase so convert it.
if (presentCharCode >= 65 && presentCharCode <= 90) {
// Convert the case by use of the above explanation.
return String.fromCharCode(presentCharCode + 32)
}
// Else return the characters without any modification.
return char
})
// Return the first converted character and remaining character string.
return firstChar + newWordChar.join('')
})
// Convert all words in a string and return it.
return stringCollections.join(' ')
}
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
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
编辑 (opens new window)
上次更新: 2022/10/28, 17:23:56