all files / random-useragent/ index.js

100% Statements 18/18
100% Branches 4/4
100% Functions 8/8
100% Lines 17/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                  1 1           213     1 218     1 206 206     1 103     1 103     1 108 71490       1 110    
/*
 * random-useragent
 * https://github.com/skratchdot/random-useragent
 *
 * Copyright (c) 2014 skratchdot
 * Licensed under the MIT license.
 */
'use strict';
 
var useragents = require('./useragent-data.json');
var rand = require('random-seed').create();
 
// cloning is slow, but it's only done when returning parsed user agent
// objects (so the data can't be changed by the end user).
// this can be a performance hit when in a loop, so use with caution.
var cloneData = function (data) {
	return JSON.parse(JSON.stringify(data));
};
 
var getData = function (filter) {
	return typeof filter === 'function' ? useragents.filter(filter) : useragents;
};
 
var getRandom = function (fn, filter) {
	var data = exports[fn](filter);
	return data.length ? data[rand.intBetween(0, data.length - 1)] : null;
};
 
exports.getRandom = function (filter) {
	return getRandom('getAll', filter);
};
 
exports.getRandomData = function (filter) {
	return cloneData(getRandom('getAllData', filter));
};
 
exports.getAll = function (filter) {
	return getData(filter).map(function (item) {
		return item.userAgent;
	});
};
 
exports.getAllData = function (filter) {
	return cloneData(getData(filter));
};