ortense
9/24/2015 - 3:26 PM

pluck

pluck

'use strict';
    
Array.prototype.pluck = function (propertName, executable, args) {
    let hasWarn = console && console.warn;
    let result = [];
    if (executable) {
        args = args || [];
        for ( let item of this ) {
            if (typeof item[propertName] === 'function') {
                result.push(item[propertName].apply(item, args));
            }
            else {
                hasWarn && console.warn(`${propertName} is not a method of object`, item);
                result.push(undefined);
            }
        }
    }
    else {
        for ( let item of this ) result.push(item[propertName]);
    }
    console.log(result);
    return result;
};
[{name:'Tony'},{name:'Matt'},{name:'Peter'}].pluck('name'); //['Tony', 'Matt', 'Peter']
[1,11,111].pluck('toString', true); //['1','11','111']
['Clint', 'Nick', 'Steve'].pluck('substring', true, [1,4]); //['lin', 'ick', 'tev']