How to use underscore

Comprehensive underscore code examples:

How to use underscore.toLower:

165
166
167
168
169
170
171
172
173
174
    return (str);
}

filters.title_case_vat_excise = function (str) {
    var _ = require('lodash');
    var tmp = _.toLower(str);
    if (tmp.indexOf("excise") > -1) {
        str = _.capitalize(_.toLower(str));
        str = str.replace("uk", "UK");
        str = str.replace("union", "Union");

How to use underscore.upperFirst:

137
138
139
140
141
142
143
144
145
146
    return (str);
}

filters.upperFirst = function (str) {
    var _ = require('lodash');
    str = _.upperFirst(str);
    return (str);
}

filters.insert_vat_excise = function (str, vat_string, excise_string) {

How to use underscore.str:

391
392
393
394
395
396
397
398
399
400
// Log the search query
// var s = new SearchLog(req.body);
// s.save();

// Trim the postcode
//var postcode = _.str.trim(postcode);

// Lat/lon
var lat = '';
var lon = '';

How to use underscore._:

1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378


Można zaimportowac całą bibliotekę:
var u = require('underscore');
var array = [1,2,3,4,5];
//teraz moge urzyć tej bibloteki ale z poziomu utworzonej 
var arrayShufle = u._.shuffle(array);
console.log(x); // wypisze tablice pomieszana





How to use underscore.chunk:

160
161
162
163
164
165
166
167
168
169
        api_key: challonge_config.api_key
    },
    validateStatus: () => true,
});
sendResponse("开始上传玩家列表至 Challonge。");
for (const chunk of _.chunk(player_list, 10)) {
    sendResponse(`开始上传玩家 ${chunk.join(', ')} 至 Challonge。`);
    await axios.post(`https://api.challonge.com/v1/tournaments/${challonge_config.tournament_id}/participants/bulk_add.json`, {
    api_key: challonge_config.api_key,
    participants: chunk.map(name => ({ name })),

How to use underscore.isFinite:

101
102
103
104
105
106
107
108
109
110
111
112
// n = max length of extension
global.extension = function (name, n) {
    var i;


    assert(_.isString(name));
    assert(_.isUndefined(n) || _.isFinite(n));


    i = name.lastIndexOf('.');
    if (i < 0 || i === 0 || (n > -1 && name.length-i-1 > n))
        i = name.length;

How to use underscore.tail:

164
165
166
167
168
169
170
171
172
173

// Call a method on every element in the container,
// passing parameters to the call method one at a
// time, like `function.call`.
call: function(method){
  this.apply(method, _.tail(arguments));
},

// Apply a method on every element in the container,
// passing parameters to the call method one at a

How to use underscore.once:

135
136
137
138
139
140
141
142
143
144
    files.writeFile(filepath, entry + "\n", 'utf8');
  }
};

// Are we running Meteor from a git checkout?
files.inCheckout = _.once(function () {
  try {
    if (files.exists(files.pathJoin(files.getCurrentToolsDir(), '.git'))) {
      return true;
    }

How to use underscore.foldl:

48
49
50
51
52
53
54
55
56
57
58
};


exports.sequence = function() {
    var parsers = Array.prototype.slice.call(arguments, 0);
    var rule = function(input) {
        var result = _.foldl(parsers, function(memo, parser) {
            var result = memo.result;
            var hasCut = memo.hasCut;
            if (!result.isSuccess()) {
                return {result: result, hasCut: hasCut};

How to use underscore.capitalize:

149
150
151
152
153
154
155
156
157
158
    return (str);
}

filters.capitalise = function (str) {
    var _ = require('lodash');
    str = _.capitalize(str);
    return (str);
}

filters.title_case = function (str) {

How to use underscore.lowerFirst:

123
124
125
126
127
128
129
130
131
132
    return (str);
}

filters.lowerFirst = function (str) {
    var _ = require('lodash');
    str = _.lowerFirst(str);
    return (str);
}

filters.lowerFirstExcept = function (str, str2) {

How to use underscore.isNull:

36
37
38
39
40
41
42
43
44
45
46
47
48
var Transaction = require('ethereumjs-tx').Transaction;
var Common = require('ethereumjs-common').default;




var isNot = function(value) {
    return (_.isUndefined(value) || _.isNull(value));
};


var Accounts = function Accounts() {
    var _this = this;

How to use underscore.isNaN:

1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
    throw new Error("Type " + name + " already present");
  customTypes[name] = factory;
};


var isInfOrNan = function (obj) {
  return _.isNaN(obj) || obj === Infinity || obj === -Infinity;
};


var builtinConverters = [
  { // Date

How to use underscore.isTypedArray:

5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false

How to use underscore.object:

49
50
51
52
53
54
55
56
57
58
59
60
	return src
}


var makeCtx = function(options, urls) {
	// Transform codepoints to hex strings
	var codepoints = _.object(_.map(options.codepoints, function(codepoint, name) {
		return [name, codepoint.toString(16)]
	}))


	return _.extend({

How to use underscore.compact:

3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
let fieldIds = _.compact(_.uniq(_.pluck(inventoryData,'fieldId')))
fieldIds.forEach(fieldId => {
    let fieldData = _.reject(inventoryData,(fieldObj)=>{
        return fieldObj.fieldId != fieldId
    })
    let values = _.compact(_.uniq(_.pluck(fieldData,'value')));
    let inventoryObject = {};
    if(fieldData && fieldData.length > 0)
    {
        inventoryObject.fieldId = fieldData[0].fieldId;

How to use underscore.chain:

208
209
210
211
212
213
214
215
216
217
    next();
}

// Actions
mapGamesToGameSummaries(games) {
    return _.chain(games)
        .map((game) => game.getSummary())
        .sortBy('createdAt')
        .sortBy('started')
        .reverse()

How to use underscore.times:

4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;

How to use underscore.intersection:

3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
const newSignals = _.difference(
    allSignals,
    renderedSignals.concat(hiddentSignals)
);
renderedSignals = renderedSignals.concat(newSignals);
renderedSignals = _.intersection(
    renderedSignals,
    allSignals
);
hiddentSignals = _.difference(

How to use underscore.memoize:

27
28
29
30
31
32
33
34
35
36
37
38
		args.push(context[p]);
	});
	return func.apply(context._this || {}, args);
};


Script.prototype.getFunction = _.memoize(function (functionArgs) {
	return Function.apply(null, functionArgs);
});


/**

How to use underscore.concat:

25
26
27
28
29
30
31
32
33

const concatSuite = new Suite('concat', opts);
const array = [0, 1, 2];

concatSuite.add('lodash', () => _.concat(array, 3, 4, 5))
  .add('underscore', () => __.concat(array, 3, 4, 5))
  .add('native', () => array.concat(3, 4, 5))
  .run({ 'async': true });
```

How to use underscore.sample:

21
22
23
24
25
26
27
28
29
30
            if (child.data.url.endsWith('jpg') || child.data.url.endsWith('jpeg') || child.data.url.endsWith('png') || child.data.url.endsWith('gif')) {
                images.push(child.data.url);
            }
        }
    });
    var image = _.sample(images);
    return image;
} else {
    return null;
}

How to use underscore.isArrayLikeObject:

3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false

How to use underscore.any:

176
177
178
179
180
181
182
183
184
185
 * Checks whether the passes card is in a legal location for the passed type of play
 * @param card
 * @param {String} playingType
 */
isCardInPlayableLocation(card, playingType) {
    return _.any(
        this.playableLocations,
        (location) =>
            (!playingType || location.playingType === playingType) && location.contains(card)
    );

How to use underscore.isBuffer:

3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false

How to use underscore.eq:

5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false

How to use underscore.pairs:

79
80
81
82
83
84
85
86
87
88
89
//async function savePageMods(pageMods) {
//	pageMods = pageMods || glPageMods;
//	const toBeSavedObj = _.mapObject(pageMods, (val, key) => {
//		return val.toString();
//	});
//	const toBeSavedStr = "module.exports = {" + _.pairs(toBeSavedObj).map(x => ("\"" + x[0] + "\": " + x[1])).join(",\n") + "}";
//	return await fs.promises.writeFile(pageModsF, toBeSavedStr, "utf8");
//}


// END service Funcs

How to use underscore.first:

95
96
97
98
99
100
101
102
103
104
} else {
    var paths;

    if (!_.isEmpty(path.match(/^\[\d\]/))) {
        paths = path.replace(/^[\[\]]/g, '').split(/\./);
        nPath = _.first(paths[0].replace(/\]/, ''));
    } else {
        paths = path.split(/[\.\[]/);
        nPath = _.first(paths);
    }

How to use underscore.without:

163
164
165
166
167
168
169
170
171
        hidefile.hideSync(process.cwd().replace(/\\/g, "/") + "/.pinesuhistory/");
    }
},

createGitignore: async () => {
    const treeList = _und.without(fs.readdirSync(process.cwd()), '.git', '.gitignore');

    if (treeList.length) {
        const answers = await inquirer.askIgnoreFiles(treeList);

How to use underscore.isArrayLike:

3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true