Creating Polyfills

Video

JavaScript Notes

JavaScript
    /************************************************ 
    What is a Polyfill – adding a method to some existing object 
    How to create a Polyfill
    Array – justLetter – only keep Strings with a specific letter
    Date – f$$kinDay – return the day of the week with prefix
    **************************************************/ 
    
    let log = console.log;

    if(!Array.prototype.justLetter){
        log('justLetter method missing');
     
        Array.prototype.justLetter = function (letter ){	// creating the new method in the Array prototype 
            let arr = this.filter( (item) => {
            if (typeOf item != 'string') return false;
                return item.indexOf(letter) > -1;
            } );
        return arr;
        }
    }
    let names = ['abc', 'def', 'ghi', 'cab', 'dac'];
    log(names);
    log (names.justLetter('a'));	                        // returns the filtered array: ['abc', 'cab', 'dac']
    
    if(!Date.prototype.f$$kinDay){
        log('f$$kinDay method missing');

        Date.prototype.f$$kinDay = function ( ) { 
            switch(this.getDay( )){
                case 0:
                    return 'Today is Sunday';
                case 1:
                    return 'Today is Monday';
                case 2:
                    return 'Today is Tuesday';
                case 3:
                    return 'Today is Wednesday';
                case 4:
                    return 'Today is Thursday';
                case 5:
                    return 'Today is Friday';
                case 6:
                    return 'Today is Saturday'; 
            }
        }
    }
     
    log(new Date( ).f$$kinDay( ));