function reverseStr(str) { // str = "world"; // step 1: split the string by using of String.prototype.split() let splitStr = str.split(""); /* splitStr = str.split(""); ["w", "o", "r", "l","d"] */ //step 2: reverse the new created array by String.prototype.reverse() let reverseArr = splitStr.reverse(); /* reverseArr = splitStr.reverse(); ["d", "l", "r", "o","w"] */ //step 3: join the reverseArr by the using of String.prototype.join() let joinStr = reverseArr.join(""); /* joinStr = reverseArr.join(""); "dlrow" */ return joinStr; }
Reverse a string by using three default or built-in functions:
Perform a binary search within an array
function binary_Search(items, value){ var firstIndex = 0, lastIndex = items.length - 1, middleIndex = Math.floor((lastIndex + firstIndex)/2); while(items[middleIndex] != value && firstIndex < lastIndex) { if (value < items[middleIndex]) { lastIndex = middleIndex - 1; } else if (value > items[middleIndex]) { firstIndex = middleIndex + 1; } middleIndex = Math.floor((lastIndex + firstIndex)/2); } return (items[middleIndex] != value) ? -1 : middleIndex; } var items = [1, 2, 3, 4, 5, 7, 8, 9]; console.log(binary_Search(items, 1)); console.log(binary_Search(items, 5));
Find the leap years from a given range of years
function leap_year_range(st_year, end_year) {
var year_range = [];
for (var i = st_year; i <= end_year; i++)
{
year_range.push(i);
}
var new_array = [];
year_range.forEach(
function(year)
{
if (test_LeapYear(year))
new_array.push(year);
});
return new_array;
}
function test_LeapYear(year) {
if ((year % 4 === 0 && year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) {
return year;
} else {
return false;
}
}
console.log(leap_year_range(2000,2012));
var year_range = [];
for (var i = st_year; i <= end_year; i++)
{
year_range.push(i);
}
var new_array = [];
year_range.forEach(
function(year)
{
if (test_LeapYear(year))
new_array.push(year);
});
return new_array;
}
function test_LeapYear(year) {
if ((year % 4 === 0 && year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) {
return year;
} else {
return false;
}
}
console.log(leap_year_range(2000,2012));
Subscribe to:
Posts (Atom)