React ErrorBoundary code snippet


import React, { Component } from 'react';

class ErrorBoundary extends Component {
    state = {
        hasError: false,
        errorMessage: ''
    }

    componentDidCatch = (errorinfo=> {
        this.setState({hasError: trueerrorMessage: error});
    }

    render() {
        if (this.state.hasError) {
            return <h1>{this.state.errorMessage}</h1>;
        } else {
            return this.props.children;
        }
    }
}

export default ErrorBoundary;

Reverse a string by using three default or built-in functions:

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;  }

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));