Search code examples
javascriptdictionarystrategy-pattern

JavaScript stragegy pattern with dictionary


In C# I use strategy pattern with dictionary like this:

namespace NowListeningParserTool.Classes
{
using System.Collections.Generic;

public class WebsiteDictionary
{
    private readonly Dictionary<string, WebsiteParser> _website = new Dictionary<string, WebsiteParser>();

    public WebsiteDictionary()
    {
        _website.Add("YouTube", new YoutubeWebsiteParser());
        _website.Add("977 Music", new NineNineSevenMusicWebsiteParser());
        _website.Add("Grooveshark", new GroovesharkWebsiteParser());
        _website.Add("Sky.FM", new SkyfmWebsiteParser());
        _website.Add("iHeart", new IheartWebsiteParser());
        _website.Add("Live365", new LiveThreeSixFiveWebsiteParser());
        _website.Add("Pandora", new PandoraWebsiteParser());
        _website.Add("Spotify", new SpotifyWebsiteParser());
    }

    public string GetArtistAndTitle(string website, string browser, string stringToParse)
    {
        return _website[website].GetArtistAndTitle(browser, stringToParse, website);
    }

    public string GetWebsiteLogoUri(string website)
    {
        return _website[website].WebsiteLogoUri;
    }
}
}

WebsiteParser is abstract class.

What would be the syntax for this in JavaScript? For example I have multiple IF statements in JavaScript:

function getWebsite() {
    if (document.URL.indexOf('grooveshark.com') >= 0) return getTrackGrooveshark();
    if (document.URL.indexOf('977music.com') >= 0) return getTrack977Music();
    if (document.URL.indexOf('sky.fm/play') >= 0) return getTrackSkyFm();
    if (document.URL.indexOf('iheart.com') >= 0) return getTrackIHeart();
    if (document.URL.indexOf('live365.com') >= 0) return getTrackLive365();
    if (document.URL.indexOf('youtube.com') >= 0) return getTrackYoutube();
    if (document.URL.indexOf('pandora.com') >= 0) return getTrackPandora();
    if (document.URL.indexOf('spotify.com') >= 0) return getTrackSpotify();
}

...that I really don't like, and would like to use the same approach as I did in C# for eliminating these ugly IFs.

Cheers.


Solution

  • Perhaps something like this, but I dont have enough details to know if this approach will work or not for you. However, it shows how to use objects as key/value stores.

    var fetchingStrategies = {
        'grooveshark.com': function () {
            return 'grooving!';
        },
        'youtube.com': function () {
            return 'youtubing!';
        }
    };
    
    //execute fetching strategy based on domain
    fetchingStrategies['youtube.com']();
    

    Obviously you can replace the hard-coded 'youtube.com' string by a variable that would hold the correct domain for the lookup.