JS Foundation: implementation of toLowerCase and toUpperCase

Keywords: Javascript ascii encoding

I. thinking caused by one question

Today, I ran into a problem in leetCode

Original question link: https://leetcode.com/problems...

This problem requires the implementation of a function from upper case to lower case. At that time, the first thing that came to mind was that js did not provide a
toLowerCase function? So I wrote down the answer without hesitation:

/**
 * @param {string} str
 * @return {string}
 */
var toLowerCase = function(str) {
    return str.toLowerCase();
};

but, I don't think it's so simple, unless the author's head is jammed by the door, so I think, how does the toLowerCase of js come true?

II. ASCII coding

After consulting the data, I know that all the characters of the computer are based on ASCII encoding. Here is the mapping table of ASCII basic encoding:

At this time, it is not difficult to find that the decimal system of ASCII encoding of a-z and a-z is just 32 different, so our implementation idea is to convert the upper case to decimal encoding, then to decimal encoding of lower case letters, and finally to get lower case letters. js has two functions to implement these two transformations:

String.fromCharCode(num1, ..., numN) //Convert the code to the corresponding string

str.charCodeAt(index)  //Get the encoding of the string

Next, let's do it.

3. Code implementation:

  • toLowerCase():
/**
 * @param {string} str
 * @return {string}
 */
var toLowerCase = function(str) {
  // ASCII code difference between upper and lower case 32
  let arr = str.split('');
  let AscCode;
  let maxCode = 'Z'.charCodeAt();
  let minCode = 'A'.charCodeAt();
  for (let i = 0; i < arr.length; i++) {
    // Convert to ASCII
    AscCode = arr[i].charCodeAt();
    // Capitalized to lowercase
    if (maxCode >= AscCode && minCode <= AscCode) {
      arr[i] = String.fromCharCode(AscCode+32);
    }
  }
  return arr.join('');
};
  • toUpperCase():
/**
 * @param {string} str
 * @return {string}
 */
var toLowerCase = function(str) {
  // ASCII code difference between upper and lower case 32
  let arr = str.split('');
  let AscCode;
  let maxCode = 'a'.charCodeAt();
  let minCode = 'z'.charCodeAt();
  for (let i = 0; i < arr.length; i++) {
    // Convert to ASCII
    AscCode = arr[i].charCodeAt();
    // Capitalized to lowercase
    if (maxCode >= AscCode && minCode <= AscCode) {
      arr[i] = String.fromCharCode(AscCode-32);
    }
  }
  return arr.join('');
};

I can brush the question bank and exchange with others who are interested: https://www.yuque.com/u46795/...

Posted by -Mike- on Fri, 06 Dec 2019 07:23:23 -0800