Find all occurrences of needle in haystack by char

by Brandon Shelley

JavaScript

function search(needle, haystack) {
    var needles = needle.split('');
    var haystacks = haystack.split('');
    var matches = [];
    var nI = 0;
    var hI = 0;
    for (hI = 0; hI < haystacks.length; hI++) {
        for (nI = 0; nI < needles.length; nI++) {
            if (haystacks[hI] === needles[nI]) {
                matches.push(nI);
            } else {
                continue;
            }
        }
    }
    matches = matches.reduce(function (acc, el, index) {
        var cur = acc.map[el];
        if (!cur) {
            acc.map[el] = cur = [];
            acc.res.push(cur);
        }
        cur.push(index);
        return acc;
    }, {
        res: [],
        map: {}
    }).res;
    return matches;
}

function allPossibleCases(arr) {
    return combinations(arr).map(function (combination) {
        return combination.join(" ");
    });
}

function combinations(array) {
    if (!array.length) {
        return [];
    }

    array = array.map(function (item) {
        return item instanceof Array ? item : [item];
    });

    function combine(list) {
        var prefixes, combinations;

        if (list.length === 1) {
            return list[0];
        }
        prefixes = list[0];
        combinations = combine(list.slice(1));
        return prefixes.reduce(function (memo, prefix) {
            return memo.concat(combinations.map(function (combination) {
                return [prefix].concat(combination);
            }))
        }, []);
    }

    return combine(array);
}

var r = allPossibleCases(search("abc", "aabcc"));

console.log(r);
alert("Number of matches: " + r.length);