Don't LeetCode Yet - 6 - DIY Built-In Functions
Understand and try to build the built-in functions/methods by our selves.
Built-in Array/String Methods
Array.map()
“The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.”
Need some time for NOOBS to get used to the usage of CALLBACK functions.
The .map()
can create a new array.
example:
let arr = [1,2,3,4,5] |
This is the same as:
arr.map(double) |
String.repeat
REPEAT a string!
let str = "ABCDE" |
Same as:
"ABCDE".repeat(3) |
Array.lastIndexOf
Related to .indexOf
method.
console.log([1,2,3,1].indexOf(4)) |
So the .lastIndexOf
finds the element starting from the last one.
let arr = [1,2,3,1] |
Same as:
console.log(arr.lastIndexOf(1) |
Project Unit 6
LIOJ 1036 Array.reverse
function reverse(arr) |
LIOJ 1037 Array.filter
I accidentally used the built-in .filter
method when I try to solve the problem the first time.
let newArr = orgArr.filter(findthenum) |
This is actually a good practice to get familiar with the basic of how to use the callback function.
- Main function:
myFilter(arr, findTarget)
, no need to pass in any argument when calling the callback(findTarget
in this case) - Function used as callback in the main function:
findTarget
- Check if callback function returns anything, if yes push it into the new array.
Some improvements:
return n != target
is the same asif (n != target){ return n}
The instructor talked about the “arrow function” in ES6. And how to use the filter method.
An example of the usage of .filter()
is arr.filter(x => x > 2)
.
The x => x > 2
is an arrow function.
So the findTarget()
function can also be written as:let findTarget = n => n !== target
Or we can also directly put it in the myFilter()
function: function myFilter(arr, n => n !== target)
LIOJ 1038 Array.indexOf
EASY! If you can solve problem 1037. Don’t even need a callback function, can directly give the target as argument.
LIOJ 1039, 1040, 1042
Array.fill, Array.join, String.toLowerCase
[1,2,3,4].join(“/“) => “1/2/3/4”
LIOJ 1041 Array.trim
I tried to count the white space before the words and after the words. Then make a new string out of those index number.
for (i = preCounter; i < orgString.length-postCounter; i++){ |
Instructor trim the white space before the words first then trim the white space after the words. Test if we MEET a letter!
LIOJ 1043 String.endsWith
Instructor’s solution:
...... |
LIOJ 1044, 1045
String.padEnd, String.slice