Best Python code snippet using localstack_python
sorted.js
Source:sorted.js  
1'use strict';2var	async = require('async');3var assert = require('assert');4var db = require('../mocks/databasemock');5describe('Sorted Set methods', function () {6	before(function (done) {7		async.parallel([8			function (next) {9				db.sortedSetAdd('sortedSetTest1', [1.1, 1.2, 1.3], ['value1', 'value2', 'value3'], next);10			},11			function (next) {12				db.sortedSetAdd('sortedSetTest2', [1, 4], ['value1', 'value4'], next);13			},14			function (next) {15				db.sortedSetAdd('sortedSetTest3', [2, 4], ['value2', 'value4'], next);16			},17			function (next) {18				db.sortedSetAdd('sortedSetTest4', [1, 1, 2, 3, 5], ['b', 'a', 'd', 'e', 'c'], next);19			},20			function (next) {21				db.sortedSetAdd('sortedSetLex', [0, 0, 0, 0], ['a', 'b', 'c', 'd'], next);22			},23		], done);24	});25	describe('sortedSetAdd()', function () {26		it('should add an element to a sorted set', function (done) {27			db.sortedSetAdd('sorted1', 1, 'value1', function (err) {28				assert.equal(err, null);29				assert.equal(arguments.length, 1);30				done();31			});32		});33		it('should add two elements to a sorted set', function (done) {34			db.sortedSetAdd('sorted2', [1, 2], ['value1', 'value2'], function (err) {35				assert.equal(err, null);36				assert.equal(arguments.length, 1);37				done();38			});39		});40	});41	describe('sortedSetsAdd()', function () {42		it('should add an element to two sorted sets', function (done) {43			db.sortedSetsAdd(['sorted1', 'sorted2'], 3, 'value3', function (err) {44				assert.equal(err, null);45				assert.equal(arguments.length, 1);46				done();47			});48		});49	});50	describe('getSortedSetRange()', function () {51		it('should return the lowest scored element', function (done) {52			db.getSortedSetRange('sortedSetTest1', 0, 0, function (err, value) {53				assert.equal(err, null);54				assert.equal(arguments.length, 2);55				assert.deepEqual(value, ['value1']);56				done();57			});58		});59		it('should return elements sorted by score lowest to highest', function (done) {60			db.getSortedSetRange('sortedSetTest1', 0, -1, function (err, values) {61				assert.equal(err, null);62				assert.equal(arguments.length, 2);63				assert.deepEqual(values, ['value1', 'value2', 'value3']);64				done();65			});66		});67		it('should return empty array if set does not exist', function (done) {68			db.getSortedSetRange('doesnotexist', 0, -1, function (err, values) {69				assert.ifError(err);70				assert(Array.isArray(values));71				assert.equal(values.length, 0);72				done();73			});74		});75		it('should handle negative start/stop', function (done) {76			db.sortedSetAdd('negatives', [1, 2, 3, 4, 5], ['1', '2', '3', '4', '5'], function (err) {77				assert.ifError(err);78				db.getSortedSetRange('negatives', -2, -4, function (err, data) {79					assert.ifError(err);80					assert.deepEqual(data, []);81					done();82				});83			});84		});85		it('should handle negative start/stop', function (done) {86			db.getSortedSetRange('negatives', -4, -2, function (err, data) {87				assert.ifError(err);88				assert.deepEqual(data, ['2', '3', '4']);89				done();90			});91		});92		it('should handle negative start/stop', function (done) {93			db.getSortedSetRevRange('negatives', -4, -2, function (err, data) {94				assert.ifError(err);95				assert.deepEqual(data, ['4', '3', '2']);96				done();97			});98		});99		it('should handle negative start/stop', function (done) {100			db.getSortedSetRange('negatives', -5, -1, function (err, data) {101				assert.ifError(err);102				assert.deepEqual(data, ['1', '2', '3', '4', '5']);103				done();104			});105		});106		it('should handle negative start/stop', function (done) {107			db.getSortedSetRange('negatives', 0, -2, function (err, data) {108				assert.ifError(err);109				assert.deepEqual(data, ['1', '2', '3', '4']);110				done();111			});112		});113	});114	describe('getSortedSetRevRange()', function () {115		it('should return the highest scored element', function (done) {116			db.getSortedSetRevRange('sortedSetTest1', 0, 0, function (err, value) {117				assert.equal(err, null);118				assert.equal(arguments.length, 2);119				assert.deepEqual(value, ['value3']);120				done();121			});122		});123		it('should return elements sorted by score highest to lowest', function (done) {124			db.getSortedSetRevRange('sortedSetTest1', 0, -1, function (err, values) {125				assert.equal(err, null);126				assert.equal(arguments.length, 2);127				assert.deepEqual(values, ['value3', 'value2', 'value1']);128				done();129			});130		});131	});132	describe('getSortedSetRangeWithScores()', function () {133		it('should return array of elements sorted by score lowest to highest with scores', function (done) {134			db.getSortedSetRangeWithScores('sortedSetTest1', 0, -1, function (err, values) {135				assert.equal(err, null);136				assert.equal(arguments.length, 2);137				assert.deepEqual(values, [{ value: 'value1', score: 1.1 }, { value: 'value2', score: 1.2 }, { value: 'value3', score: 1.3 }]);138				done();139			});140		});141	});142	describe('getSortedSetRevRangeWithScores()', function () {143		it('should return array of elements sorted by score highest to lowest with scores', function (done) {144			db.getSortedSetRevRangeWithScores('sortedSetTest1', 0, -1, function (err, values) {145				assert.equal(err, null);146				assert.equal(arguments.length, 2);147				assert.deepEqual(values, [{ value: 'value3', score: 1.3 }, { value: 'value2', score: 1.2 }, { value: 'value1', score: 1.1 }]);148				done();149			});150		});151	});152	describe('getSortedSetRangeByScore()', function () {153		it('should get count elements with score between min max sorted by score lowest to highest', function (done) {154			db.getSortedSetRangeByScore('sortedSetTest1', 0, -1, '-inf', 1.2, function (err, values) {155				assert.equal(err, null);156				assert.equal(arguments.length, 2);157				assert.deepEqual(values, ['value1', 'value2']);158				done();159			});160		});161		it('should return empty array if set does not exist', function (done) {162			db.getSortedSetRangeByScore('doesnotexist', 0, -1, '-inf', 0, function (err, values) {163				assert.ifError(err);164				assert(Array.isArray(values));165				assert.equal(values.length, 0);166				done();167			});168		});169	});170	describe('getSortedSetRevRangeByScore()', function () {171		it('should get count elements with score between max min sorted by score highest to lowest', function (done) {172			db.getSortedSetRevRangeByScore('sortedSetTest1', 0, -1, '+inf', 1.2, function (err, values) {173				assert.equal(err, null);174				assert.equal(arguments.length, 2);175				assert.deepEqual(values, ['value3', 'value2']);176				done();177			});178		});179	});180	describe('getSortedSetRangeByScoreWithScores()', function () {181		it('should get count elements with score between min max sorted by score lowest to highest with scores', function (done) {182			db.getSortedSetRangeByScoreWithScores('sortedSetTest1', 0, -1, '-inf', 1.2, function (err, values) {183				assert.equal(err, null);184				assert.equal(arguments.length, 2);185				assert.deepEqual(values, [{ value: 'value1', score: 1.1 }, { value: 'value2', score: 1.2 }]);186				done();187			});188		});189	});190	describe('getSortedSetRevRangeByScoreWithScores()', function () {191		it('should get count elements with score between max min sorted by score highest to lowest', function (done) {192			db.getSortedSetRevRangeByScoreWithScores('sortedSetTest1', 0, -1, '+inf', 1.2, function (err, values) {193				assert.equal(err, null);194				assert.equal(arguments.length, 2);195				assert.deepEqual(values, [{ value: 'value3', score: 1.3 }, { value: 'value2', score: 1.2 }]);196				done();197			});198		});199	});200	describe('sortedSetCount()', function () {201		it('should return 0 for a sorted set that does not exist', function (done) {202			db.sortedSetCount('doesnotexist', 0, 10, function (err, count) {203				assert.equal(err, null);204				assert.equal(arguments.length, 2);205				assert.equal(count, 0);206				done();207			});208		});209		it('should return number of elements between scores min max inclusive', function (done) {210			db.sortedSetCount('sortedSetTest1', '-inf', 1.2, function (err, count) {211				assert.equal(err, null);212				assert.equal(arguments.length, 2);213				assert.equal(count, 2);214				done();215			});216		});217		it('should return number of elements between scores -inf +inf inclusive', function (done) {218			db.sortedSetCount('sortedSetTest1', '-inf', '+inf', function (err, count) {219				assert.equal(err, null);220				assert.equal(arguments.length, 2);221				assert.equal(count, 3);222				done();223			});224		});225	});226	describe('sortedSetCard()', function () {227		it('should return 0 for a sorted set that does not exist', function (done) {228			db.sortedSetCard('doesnotexist', function (err, count) {229				assert.equal(err, null);230				assert.equal(arguments.length, 2);231				assert.equal(count, 0);232				done();233			});234		});235		it('should return number of elements in a sorted set', function (done) {236			db.sortedSetCard('sortedSetTest1', function (err, count) {237				assert.equal(err, null);238				assert.equal(arguments.length, 2);239				assert.equal(count, 3);240				done();241			});242		});243	});244	describe('sortedSetsCard()', function () {245		it('should return the number of elements in sorted sets', function (done) {246			db.sortedSetsCard(['sortedSetTest1', 'sortedSetTest2', 'doesnotexist'], function (err, counts) {247				assert.equal(err, null);248				assert.equal(arguments.length, 2);249				assert.deepEqual(counts, [3, 2, 0]);250				done();251			});252		});253	});254	describe('sortedSetRank()', function () {255		it('should return falsy if sorted set does not exist', function (done) {256			db.sortedSetRank('doesnotexist', 'value1', function (err, rank) {257				assert.equal(err, null);258				assert.equal(arguments.length, 2);259				assert.equal(!!rank, false);260				done();261			});262		});263		it('should return falsy if element isnt in sorted set', function (done) {264			db.sortedSetRank('sortedSetTest1', 'value5', function (err, rank) {265				assert.equal(err, null);266				assert.equal(arguments.length, 2);267				assert.equal(!!rank, false);268				done();269			});270		});271		it('should return the rank of the element in the sorted set sorted by lowest to highest score', function (done) {272			db.sortedSetRank('sortedSetTest1', 'value1', function (err, rank) {273				assert.equal(err, null);274				assert.equal(arguments.length, 2);275				assert.equal(rank, 0);276				done();277			});278		});279		it('should return the rank sorted by the score and then the value (a)', function (done) {280			db.sortedSetRank('sortedSetTest4', 'a', function (err, rank) {281				assert.equal(err, null);282				assert.equal(arguments.length, 2);283				assert.equal(rank, 0);284				done();285			});286		});287		it('should return the rank sorted by the score and then the value (b)', function (done) {288			db.sortedSetRank('sortedSetTest4', 'b', function (err, rank) {289				assert.equal(err, null);290				assert.equal(arguments.length, 2);291				assert.equal(rank, 1);292				done();293			});294		});295		it('should return the rank sorted by the score and then the value (c)', function (done) {296			db.sortedSetRank('sortedSetTest4', 'c', function (err, rank) {297				assert.equal(err, null);298				assert.equal(arguments.length, 2);299				assert.equal(rank, 4);300				done();301			});302		});303	});304	describe('sortedSetRevRank()', function () {305		it('should return falsy if sorted set doesnot exist', function (done) {306			db.sortedSetRevRank('doesnotexist', 'value1', function (err, rank) {307				assert.equal(err, null);308				assert.equal(arguments.length, 2);309				assert.equal(!!rank, false);310				done();311			});312		});313		it('should return falsy if element isnt in sorted set', function (done) {314			db.sortedSetRevRank('sortedSetTest1', 'value5', function (err, rank) {315				assert.equal(err, null);316				assert.equal(arguments.length, 2);317				assert.equal(!!rank, false);318				done();319			});320		});321		it('should return the rank of the element in the sorted set sorted by highest to lowest score', function (done) {322			db.sortedSetRevRank('sortedSetTest1', 'value1', function (err, rank) {323				assert.equal(err, null);324				assert.equal(arguments.length, 2);325				assert.equal(rank, 2);326				done();327			});328		});329	});330	describe('sortedSetsRanks()', function () {331		it('should return the ranks of values in sorted sets', function (done) {332			db.sortedSetsRanks(['sortedSetTest1', 'sortedSetTest2'], ['value1', 'value4'], function (err, ranks) {333				assert.equal(err, null);334				assert.equal(arguments.length, 2);335				assert.deepEqual(ranks, [0, 1]);336				done();337			});338		});339	});340	describe('sortedSetRanks()', function () {341		it('should return the ranks of values in a sorted set', function (done) {342			db.sortedSetRanks('sortedSetTest1', ['value2', 'value1', 'value3', 'value4'], function (err, ranks) {343				assert.equal(err, null);344				assert.equal(arguments.length, 2);345				assert.deepEqual(ranks, [1, 0, 2, null]);346				done();347			});348		});349	});350	describe('sortedSetScore()', function () {351		it('should return falsy if sorted set does not exist', function (done) {352			db.sortedSetScore('doesnotexist', 'value1', function (err, score) {353				assert.equal(err, null);354				assert.equal(arguments.length, 2);355				assert.equal(!!score, false);356				assert.strictEqual(score, null);357				done();358			});359		});360		it('should return falsy if element is not in sorted set', function (done) {361			db.sortedSetScore('sortedSetTest1', 'value5', function (err, score) {362				assert.equal(err, null);363				assert.equal(arguments.length, 2);364				assert.equal(!!score, false);365				assert.strictEqual(score, null);366				done();367			});368		});369		it('should return the score of an element', function (done) {370			db.sortedSetScore('sortedSetTest1', 'value2', function (err, score) {371				assert.equal(err, null);372				assert.equal(arguments.length, 2);373				assert.equal(score, 1.2);374				done();375			});376		});377		it('should not error if key is undefined', function (done) {378			db.sortedSetScore(undefined, 1, function (err, score) {379				assert.ifError(err);380				assert.strictEqual(score, null);381				done();382			});383		});384		it('should not error if value is undefined', function (done) {385			db.sortedSetScore('sortedSetTest1', undefined, function (err, score) {386				assert.ifError(err);387				assert.strictEqual(score, null);388				done();389			});390		});391	});392	describe('sortedSetsScore()', function () {393		it('should return the scores of value in sorted sets', function (done) {394			db.sortedSetsScore(['sortedSetTest1', 'sortedSetTest2', 'doesnotexist'], 'value1', function (err, scores) {395				assert.equal(err, null);396				assert.equal(arguments.length, 2);397				assert.deepEqual(scores, [1.1, 1, null]);398				done();399			});400		});401		it('should return scores even if some keys are undefined', function (done) {402			db.sortedSetsScore(['sortedSetTest1', undefined, 'doesnotexist'], 'value1', function (err, scores) {403				assert.equal(err, null);404				assert.equal(arguments.length, 2);405				assert.deepEqual(scores, [1.1, null, null]);406				done();407			});408		});409	});410	describe('sortedSetScores()', function () {411		before(function (done) {412			db.sortedSetAdd('zeroScore', 0, 'value1', done);413		});414		it('should return 0 if score is 0', function (done) {415			db.sortedSetScores('zeroScore', ['value1'], function (err, scores) {416				assert.ifError(err);417				assert.equal(0, scores[0]);418				done();419			});420		});421		it('should return the scores of value in sorted sets', function (done) {422			db.sortedSetScores('sortedSetTest1', ['value2', 'value1', 'doesnotexist'], function (err, scores) {423				assert.equal(err, null);424				assert.equal(arguments.length, 2);425				assert.deepEqual(scores, [1.2, 1.1, null]);426				done();427			});428		});429		it('should return scores even if some values are undefined', function (done) {430			db.sortedSetScores('sortedSetTest1', ['value2', undefined, 'doesnotexist'], function (err, scores) {431				assert.equal(err, null);432				assert.equal(arguments.length, 2);433				assert.deepEqual(scores, [1.2, null, null]);434				done();435			});436		});437	});438	describe('isSortedSetMember()', function () {439		before(function (done) {440			db.sortedSetAdd('zeroscore', 0, 'itemwithzeroscore', done);441		});442		it('should return false if sorted set does not exist', function (done) {443			db.isSortedSetMember('doesnotexist', 'value1', function (err, isMember) {444				assert.ifError(err);445				assert.equal(arguments.length, 2);446				assert.equal(isMember, false);447				done();448			});449		});450		it('should return false if element is not in sorted set', function (done) {451			db.isSortedSetMember('sorted2', 'value5', function (err, isMember) {452				assert.ifError(err);453				assert.equal(arguments.length, 2);454				assert.equal(isMember, false);455				done();456			});457		});458		it('should return true if element is in sorted set', function (done) {459			db.isSortedSetMember('sortedSetTest1', 'value2', function (err, isMember) {460				assert.ifError(err);461				assert.equal(arguments.length, 2);462				assert.strictEqual(isMember, true);463				done();464			});465		});466		it('should return true if element is in sorted set with sre 0', function (done) {467			db.isSortedSetMember('zeroscore', 'itemwithzeroscore', function (err, isMember) {468				assert.ifError(err);469				assert.strictEqual(isMember, true);470				done();471			});472		});473	});474	describe('isSortedSetMembers()', function () {475		it('should return an array of booleans indicating membership', function (done) {476			db.isSortedSetMembers('sortedSetTest1', ['value1', 'value2', 'value5'], function (err, isMembers) {477				assert.equal(err, null);478				assert.equal(arguments.length, 2);479				assert.deepEqual(isMembers, [true, true, false]);480				done();481			});482		});483	});484	describe('isMemberOfSortedSets', function () {485		it('should return true for members false for non members', function (done) {486			db.isMemberOfSortedSets(['doesnotexist', 'sortedSetTest1', 'sortedSetTest2'], 'value2', function (err, isMembers) {487				assert.equal(err, null);488				assert.equal(arguments.length, 2);489				assert.deepEqual(isMembers, [false, true, false]);490				done();491			});492		});493	});494	describe('getSortedSetsMembers', function () {495		it('should return members of multiple sorted sets', function (done) {496			db.getSortedSetsMembers(['doesnotexist', 'sortedSetTest1'], function (err, sortedSets) {497				assert.equal(err, null);498				assert.equal(arguments.length, 2);499				assert.deepEqual(sortedSets[0], []);500				sortedSets[0].forEach(function (element) {501					assert.notEqual(['value1', 'value2', 'value3'].indexOf(element), -1);502				});503				done();504			});505		});506	});507	describe('sortedSetUnionCard', function () {508		it('should return the number of elements in the union', function (done) {509			db.sortedSetUnionCard(['sortedSetTest2', 'sortedSetTest3'], function (err, count) {510				assert.ifError(err);511				assert.equal(count, 3);512				done();513			});514		});515	});516	describe('getSortedSetUnion()', function () {517		it('should return an array of values from both sorted sets sorted by scores lowest to highest', function (done) {518			db.getSortedSetUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1 }, function (err, values) {519				assert.equal(err, null);520				assert.equal(arguments.length, 2);521				assert.deepEqual(values, ['value1', 'value2', 'value4']);522				done();523			});524		});525		it('should return an array of values and scores from both sorted sets sorted by scores lowest to highest', function (done) {526			db.getSortedSetUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1, withScores: true }, function (err, data) {527				assert.equal(err, null);528				assert.equal(arguments.length, 2);529				assert.deepEqual(data, [{ value: 'value1', score: 1 }, { value: 'value2', score: 2 }, { value: 'value4', score: 8 }]);530				done();531			});532		});533	});534	describe('getSortedSetRevUnion()', function () {535		it('should return an array of values from both sorted sets sorted by scores highest to lowest', function (done) {536			db.getSortedSetRevUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1 }, function (err, values) {537				assert.equal(err, null);538				assert.equal(arguments.length, 2);539				assert.deepEqual(values, ['value4', 'value2', 'value1']);540				done();541			});542		});543	});544	describe('sortedSetIncrBy()', function () {545		it('should create a sorted set with a field set to 1', function (done) {546			db.sortedSetIncrBy('sortedIncr', 1, 'field1', function (err, newValue) {547				assert.equal(err, null);548				assert.equal(arguments.length, 2);549				assert.strictEqual(newValue, 1);550				db.sortedSetScore('sortedIncr', 'field1', function (err, score) {551					assert.equal(err, null);552					assert.strictEqual(score, 1);553					done();554				});555			});556		});557		it('should increment a field of a sorted set by 5', function (done) {558			db.sortedSetIncrBy('sortedIncr', 5, 'field1', function (err, newValue) {559				assert.equal(err, null);560				assert.equal(arguments.length, 2);561				assert.strictEqual(newValue, 6);562				db.sortedSetScore('sortedIncr', 'field1', function (err, score) {563					assert.equal(err, null);564					assert.strictEqual(score, 6);565					done();566				});567			});568		});569	});570	describe('sortedSetRemove()', function () {571		before(function (done) {572			db.sortedSetAdd('sorted3', [1, 2], ['value1', 'value2'], done);573		});574		it('should remove an element from a sorted set', function (done) {575			db.sortedSetRemove('sorted3', 'value2', function (err) {576				assert.equal(err, null);577				assert.equal(arguments.length, 1);578				db.isSortedSetMember('sorted3', 'value2', function (err, isMember) {579					assert.equal(err, null);580					assert.equal(isMember, false);581					done();582				});583			});584		});585		it('should remove multiple values from multiple keys', function (done) {586			db.sortedSetAdd('multiTest1', [1, 2, 3, 4], ['one', 'two', 'three', 'four'], function (err) {587				assert.ifError(err);588				db.sortedSetAdd('multiTest2', [3, 4, 5, 6], ['three', 'four', 'five', 'six'], function (err) {589					assert.ifError(err);590					db.sortedSetRemove(['multiTest1', 'multiTest2'], ['two', 'three', 'four', 'five', 'doesnt exist'], function (err) {591						assert.ifError(err);592						db.getSortedSetsMembers(['multiTest1', 'multiTest2'], function (err, members) {593							assert.ifError(err);594							assert.equal(members[0].length, 1);595							assert.equal(members[1].length, 1);596							assert.deepEqual(members, [['one'], ['six']]);597							done();598						});599					});600				});601			});602		});603		it('should remove value from multiple keys', function (done) {604			db.sortedSetAdd('multiTest3', [1, 2, 3, 4], ['one', 'two', 'three', 'four'], function (err) {605				assert.ifError(err);606				db.sortedSetAdd('multiTest4', [3, 4, 5, 6], ['three', 'four', 'five', 'six'], function (err) {607					assert.ifError(err);608					db.sortedSetRemove(['multiTest3', 'multiTest4'], 'three', function (err) {609						assert.ifError(err);610						db.getSortedSetsMembers(['multiTest3', 'multiTest4'], function (err, members) {611							assert.ifError(err);612							assert.deepEqual(members, [['one', 'two', 'four'], ['four', 'five', 'six']]);613							done();614						});615					});616				});617			});618		});619		it('should remove multiple values from multiple keys', function (done) {620			db.sortedSetAdd('multiTest5', [1], ['one'], function (err) {621				assert.ifError(err);622				db.sortedSetAdd('multiTest6', [2], ['two'], function (err) {623					assert.ifError(err);624					db.sortedSetAdd('multiTest7', [3], ['three'], function (err) {625						assert.ifError(err);626						db.sortedSetRemove(['multiTest5', 'multiTest6', 'multiTest7'], ['one', 'two', 'three'], function (err) {627							assert.ifError(err);628							db.getSortedSetsMembers(['multiTest5', 'multiTest6', 'multiTest7'], function (err, members) {629								assert.ifError(err);630								assert.deepEqual(members, [[], [], []]);631								done();632							});633						});634					});635				});636			});637		});638	});639	describe('sortedSetsRemove()', function () {640		before(function (done) {641			async.parallel([642				async.apply(db.sortedSetAdd, 'sorted4', [1, 2], ['value1', 'value2']),643				async.apply(db.sortedSetAdd, 'sorted5', [1, 2], ['value1', 'value3']),644			], done);645		});646		it('should remove element from multiple sorted sets', function (done) {647			db.sortedSetsRemove(['sorted4', 'sorted5'], 'value1', function (err) {648				assert.equal(err, null);649				assert.equal(arguments.length, 1);650				db.sortedSetsScore(['sorted4', 'sorted5'], 'value1', function (err, scores) {651					assert.equal(err, null);652					assert.deepEqual(scores, [null, null]);653					done();654				});655			});656		});657	});658	describe('sortedSetsRemoveRangeByScore()', function () {659		before(function (done) {660			db.sortedSetAdd('sorted6', [1, 2, 3, 4, 5], ['value1', 'value2', 'value3', 'value4', 'value5'], done);661		});662		it('should remove elements with scores between min max inclusive', function (done) {663			db.sortedSetsRemoveRangeByScore(['sorted6'], 4, 5, function (err) {664				assert.ifError(err);665				assert.equal(arguments.length, 1);666				db.getSortedSetRange('sorted6', 0, -1, function (err, values) {667					assert.ifError(err);668					assert.deepEqual(values, ['value1', 'value2', 'value3']);669					done();670				});671			});672		});673		it('should remove elements with if strin score is passed in', function (done) {674			db.sortedSetAdd('sortedForRemove', [11, 22, 33], ['value1', 'value2', 'value3'], function (err) {675				assert.ifError(err);676				db.sortedSetsRemoveRangeByScore(['sortedForRemove'], '22', '22', function (err) {677					assert.ifError(err);678					db.getSortedSetRange('sortedForRemove', 0, -1, function (err, values) {679						assert.ifError(err);680						assert.deepEqual(values, ['value1', 'value3']);681						done();682					});683				});684			});685		});686	});687	describe('getSortedSetIntersect', function () {688		before(function (done) {689			async.parallel([690				function (next) {691					db.sortedSetAdd('interSet1', [1, 2, 3], ['value1', 'value2', 'value3'], next);692				},693				function (next) {694					db.sortedSetAdd('interSet2', [4, 5, 6], ['value2', 'value3', 'value5'], next);695				},696			], done);697		});698		it('should return the intersection of two sets', function (done) {699			db.getSortedSetIntersect({700				sets: ['interSet1', 'interSet2'],701				start: 0,702				stop: -1,703			}, function (err, data) {704				assert.ifError(err);705				assert.deepEqual(['value2', 'value3'], data);706				done();707			});708		});709		it('should return the intersection of two sets with scores', function (done) {710			db.getSortedSetIntersect({711				sets: ['interSet1', 'interSet2'],712				start: 0,713				stop: -1,714				withScores: true,715			}, function (err, data) {716				assert.ifError(err);717				assert.deepEqual([{ value: 'value2', score: 6 }, { value: 'value3', score: 8 }], data);718				done();719			});720		});721		it('should return the reverse intersection of two sets', function (done) {722			db.getSortedSetRevIntersect({723				sets: ['interSet1', 'interSet2'],724				start: 0,725				stop: 2,726			}, function (err, data) {727				assert.ifError(err);728				assert.deepEqual(['value3', 'value2'], data);729				done();730			});731		});732		it('should return the intersection of two sets with scores aggregate MIN', function (done) {733			db.getSortedSetIntersect({734				sets: ['interSet1', 'interSet2'],735				start: 0,736				stop: -1,737				withScores: true,738				aggregate: 'MIN',739			}, function (err, data) {740				assert.ifError(err);741				assert.deepEqual([{ value: 'value2', score: 2 }, { value: 'value3', score: 3 }], data);742				done();743			});744		});745		it('should return the intersection of two sets with scores aggregate MAX', function (done) {746			db.getSortedSetIntersect({747				sets: ['interSet1', 'interSet2'],748				start: 0,749				stop: -1,750				withScores: true,751				aggregate: 'MAX',752			}, function (err, data) {753				assert.ifError(err);754				assert.deepEqual([{ value: 'value2', score: 4 }, { value: 'value3', score: 5 }], data);755				done();756			});757		});758		it('should return the intersection with scores modified by weights', function (done) {759			db.getSortedSetIntersect({760				sets: ['interSet1', 'interSet2'],761				start: 0,762				stop: -1,763				withScores: true,764				weights: [1, 0.5],765			}, function (err, data) {766				assert.ifError(err);767				assert.deepEqual([{ value: 'value2', score: 4 }, { value: 'value3', score: 5.5 }], data);768				done();769			});770		});771		it('should return empty array if sets do not exist', function (done) {772			db.getSortedSetIntersect({773				sets: ['interSet10', 'interSet12'],774				start: 0,775				stop: -1,776			}, function (err, data) {777				assert.ifError(err);778				assert.equal(data.length, 0);779				done();780			});781		});782		it('should return empty array if one set does not exist', function (done) {783			db.getSortedSetIntersect({784				sets: ['interSet1', 'interSet12'],785				start: 0,786				stop: -1,787			}, function (err, data) {788				assert.ifError(err);789				assert.equal(data.length, 0);790				done();791			});792		});793	});794	describe('sortedSetIntersectCard', function () {795		before(function (done) {796			async.parallel([797				function (next) {798					db.sortedSetAdd('interCard1', [0, 0, 0], ['value1', 'value2', 'value3'], next);799				},800				function (next) {801					db.sortedSetAdd('interCard2', [0, 0, 0], ['value2', 'value3', 'value4'], next);802				},803				function (next) {804					db.sortedSetAdd('interCard3', [0, 0, 0], ['value3', 'value4', 'value5'], next);805				},806				function (next) {807					db.sortedSetAdd('interCard4', [0, 0, 0], ['value4', 'value5', 'value6'], next);808				},809			], done);810		});811		it('should return # of elements in intersection', function (done) {812			db.sortedSetIntersectCard(['interCard1', 'interCard2', 'interCard3'], function (err, count) {813				assert.ifError(err);814				assert.strictEqual(count, 1);815				done();816			});817		});818		it('should return 0 if intersection is empty', function (done) {819			db.sortedSetIntersectCard(['interCard1', 'interCard4'], function (err, count) {820				assert.ifError(err);821				assert.strictEqual(count, 0);822				done();823			});824		});825	});826	describe('getSortedSetRangeByLex', function () {827		it('should return an array of all values', function (done) {828			db.getSortedSetRangeByLex('sortedSetLex', '-', '+', function (err, data) {829				assert.ifError(err);830				assert.deepEqual(data, ['a', 'b', 'c', 'd']);831				done();832			});833		});834		it('should return an array with an inclusive range by default', function (done) {835			db.getSortedSetRangeByLex('sortedSetLex', 'a', 'd', function (err, data) {836				assert.ifError(err);837				assert.deepEqual(data, ['a', 'b', 'c', 'd']);838				done();839			});840		});841		it('should return an array with an inclusive range', function (done) {842			db.getSortedSetRangeByLex('sortedSetLex', '[a', '[d', function (err, data) {843				assert.ifError(err);844				assert.deepEqual(data, ['a', 'b', 'c', 'd']);845				done();846			});847		});848		it('should return an array with an exclusive range', function (done) {849			db.getSortedSetRangeByLex('sortedSetLex', '(a', '(d', function (err, data) {850				assert.ifError(err);851				assert.deepEqual(data, ['b', 'c']);852				done();853			});854		});855		it('should return an array limited to the first two values', function (done) {856			db.getSortedSetRangeByLex('sortedSetLex', '-', '+', 0, 2, function (err, data) {857				assert.ifError(err);858				assert.deepEqual(data, ['a', 'b']);859				done();860			});861		});862	});863	describe('getSortedSetRevRangeByLex', function () {864		it('should return an array of all values reversed', function (done) {865			db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', function (err, data) {866				assert.ifError(err);867				assert.deepEqual(data, ['d', 'c', 'b', 'a']);868				done();869			});870		});871		it('should return an array with an inclusive range by default reversed', function (done) {872			db.getSortedSetRevRangeByLex('sortedSetLex', 'd', 'a', function (err, data) {873				assert.ifError(err);874				assert.deepEqual(data, ['d', 'c', 'b', 'a']);875				done();876			});877		});878		it('should return an array with an inclusive range reversed', function (done) {879			db.getSortedSetRevRangeByLex('sortedSetLex', '[d', '[a', function (err, data) {880				assert.ifError(err);881				assert.deepEqual(data, ['d', 'c', 'b', 'a']);882				done();883			});884		});885		it('should return an array with an exclusive range reversed', function (done) {886			db.getSortedSetRevRangeByLex('sortedSetLex', '(d', '(a', function (err, data) {887				assert.ifError(err);888				assert.deepEqual(data, ['c', 'b']);889				done();890			});891		});892		it('should return an array limited to the first two values reversed', function (done) {893			db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', 0, 2, function (err, data) {894				assert.ifError(err);895				assert.deepEqual(data, ['d', 'c']);896				done();897			});898		});899	});900	describe('sortedSetLexCount', function () {901		it('should return the count of all values', function (done) {902			db.sortedSetLexCount('sortedSetLex', '-', '+', function (err, data) {903				assert.ifError(err);904				assert.strictEqual(data, 4);905				done();906			});907		});908		it('should return the count with an inclusive range by default', function (done) {909			db.sortedSetLexCount('sortedSetLex', 'a', 'd', function (err, data) {910				assert.ifError(err);911				assert.strictEqual(data, 4);912				done();913			});914		});915		it('should return the count with an inclusive range', function (done) {916			db.sortedSetLexCount('sortedSetLex', '[a', '[d', function (err, data) {917				assert.ifError(err);918				assert.strictEqual(data, 4);919				done();920			});921		});922		it('should return the count with an exclusive range', function (done) {923			db.sortedSetLexCount('sortedSetLex', '(a', '(d', function (err, data) {924				assert.ifError(err);925				assert.strictEqual(data, 2);926				done();927			});928		});929	});930	describe('sortedSetRemoveRangeByLex', function () {931		before(function (done) {932			db.sortedSetAdd('sortedSetLex2', [0, 0, 0, 0, 0, 0, 0], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], done);933		});934		it('should remove an inclusive range by default', function (done) {935			db.sortedSetRemoveRangeByLex('sortedSetLex2', 'a', 'b', function (err) {936				assert.ifError(err);937				assert.equal(arguments.length, 1);938				db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) {939					assert.ifError(err);940					assert.deepEqual(data, ['c', 'd', 'e', 'f', 'g']);941					done();942				});943			});944		});945		it('should remove an inclusive range', function (done) {946			db.sortedSetRemoveRangeByLex('sortedSetLex2', '[c', '[d', function (err) {947				assert.ifError(err);948				assert.equal(arguments.length, 1);949				db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) {950					assert.ifError(err);951					assert.deepEqual(data, ['e', 'f', 'g']);952					done();953				});954			});955		});956		it('should remove an exclusive range', function (done) {957			db.sortedSetRemoveRangeByLex('sortedSetLex2', '(e', '(g', function (err) {958				assert.ifError(err);959				assert.equal(arguments.length, 1);960				db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) {961					assert.ifError(err);962					assert.deepEqual(data, ['e', 'g']);963					done();964				});965			});966		});967		it('should remove all values', function (done) {968			db.sortedSetRemoveRangeByLex('sortedSetLex2', '-', '+', function (err) {969				assert.ifError(err);970				assert.equal(arguments.length, 1);971				db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) {972					assert.ifError(err);973					assert.deepEqual(data, []);974					done();975				});976			});977		});978	});...stringset.js
Source:stringset.js  
1// Copyright 2009 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview Data structure for set of strings.16 *17 *18 * This class implements a set data structure for strings. Adding and removing19 * is O(1). It doesn't contain any bloat from {@link goog.structs.Set}, i.e.20 * it isn't optimized for IE6 garbage collector (see the description of21 * {@link goog.structs.Map#keys_} for details), and it distinguishes its22 * elements by their string value not by hash code.23 */24goog.provide('goog.structs.StringSet');25goog.require('goog.iter');26/**27 * Creates a set of strings.28 * @param {!Array=} opt_elements Elements to add to the set. The non-string29 *     items will be converted to strings, so 15 and '15' will mean the same.30 * @constructor31 */32goog.structs.StringSet = function(opt_elements) {33  /**34   * An object storing the escaped elements of the set in its keys.35   * @type {!Object}36   * @private37   */38  this.elements_ = {};39  if (opt_elements) {40    for (var i = 0; i < opt_elements.length; i++) {41      this.elements_[this.encode(opt_elements[i])] = null;42    }43  }44};45/**46 * Empty object. Referring to it is faster than creating a new empty object in47 * {@link #encode}.48 * @type {Object}49 * @private50 */51goog.structs.StringSet.EMPTY_OBJECT_ = {};52/**53 * The '__proto__' and the '__count__' keys aren't enumerable in Firefox, and54 * 'toString', 'valueOf', 'constructor', etc. aren't enumerable in IE so they55 * have to be escaped before they are added to the internal object.56 * NOTE: When a new set is created, 50-80% of the CPU time is spent in encode.57 * @param {*} element The element to escape.58 * @return {*} The escaped element or the element itself if it doesn't have to59 *     be escaped.60 * @protected61 */62goog.structs.StringSet.prototype.encode = function(element) {63  return element in goog.structs.StringSet.EMPTY_OBJECT_ ||64      String(element).charCodeAt(0) == 32 ? ' ' + element : element;65};66/**67 * Inverse function of {@link #encode}.68 * NOTE: forEach would be 30% faster in FF if the compiler inlined decode.69 * @param {string} key The escaped element used as the key of the internal70 *     object.71 * @return {string} The unescaped element.72 * @protected73 */74goog.structs.StringSet.prototype.decode = function(key) {75  return key.charCodeAt(0) == 32 ? key.substr(1) : key;76};77/**78 * Adds a single element to the set.79 * @param {*} element The element to add. It will be converted to string.80 */81goog.structs.StringSet.prototype.add = function(element) {82  this.elements_[this.encode(element)] = null;83};84/**85 * Adds a the elements of an array to this set.86 * @param {!Array} arr The array to add the elements of.87 */88goog.structs.StringSet.prototype.addArray = function(arr) {89  for (var i = 0; i < arr.length; i++) {90    this.elements_[this.encode(arr[i])] = null;91  }92};93/**94 * Adds the elements which are in {@code set1} but not in {@code set2} to this95 * set.96 * @param {!goog.structs.StringSet} set1 First set.97 * @param {!goog.structs.StringSet} set2 Second set.98 * @private99 */100goog.structs.StringSet.prototype.addDifference_ = function(set1, set2) {101  for (var key in set1.elements_) {102    if (set1.elements_.hasOwnProperty(key) &&103        !set2.elements_.hasOwnProperty(key)) {104      this.elements_[key] = null;105    }106  }107};108/**109 * Adds a the elements of a set to this set.110 * @param {!goog.structs.StringSet} stringSet The set to add the elements of.111 */112goog.structs.StringSet.prototype.addSet = function(stringSet) {113  for (var key in stringSet.elements_) {114    if (stringSet.elements_.hasOwnProperty(key)) {115      this.elements_[key] = null;116    }117  }118};119/**120 * Removes all elements of the set.121 */122goog.structs.StringSet.prototype.clear = function() {123  this.elements_ = {};124};125/**126 * @return {!goog.structs.StringSet} Clone of the set.127 */128goog.structs.StringSet.prototype.clone = function() {129  var ret = new goog.structs.StringSet;130  ret.addSet(this);131  return ret;132};133/**134 * Tells if the set contains the given element.135 * @param {*} element The element to check.136 * @return {boolean} Whether it is in the set.137 */138goog.structs.StringSet.prototype.contains = function(element) {139  return this.elements_.hasOwnProperty(this.encode(element));140};141/**142 * Tells if the set contains all elements of the array.143 * @param {!Array} arr The elements to check.144 * @return {boolean} Whether they are in the set.145 */146goog.structs.StringSet.prototype.containsArray = function(arr) {147  for (var i = 0; i < arr.length; i++) {148    if (!this.elements_.hasOwnProperty(this.encode(arr[i]))) {149      return false;150    }151  }152  return true;153};154/**155 * Tells if this set has the same elements as the given set.156 * @param {!goog.structs.StringSet} stringSet The other set.157 * @return {boolean} Whether they have the same elements.158 */159goog.structs.StringSet.prototype.equals = function(stringSet) {160  return this.isSubsetOf(stringSet) && stringSet.isSubsetOf(this);161};162/**163 * Calls a function for each element in the set.164 * @param {function(string, undefined, !goog.structs.StringSet)} f The function165 *     to call for every element. It takes the element, undefined (because sets166 *     have no notion of keys), and the set.167 * @param {Object=} opt_obj The object to be used as the value of 'this'168 *     within {@code f}.169 */170goog.structs.StringSet.prototype.forEach = function(f, opt_obj) {171  for (var key in this.elements_) {172    if (this.elements_.hasOwnProperty(key)) {173      f.call(opt_obj, this.decode(key), undefined, this);174    }175  }176};177/**178 * Counts the number of elements in the set in linear time.179 * NOTE: getCount is always called at most once per set instance in google3.180 * If this usage pattern won't change, the linear getCount implementation is181 * better, because182 * <li>populating a set and getting the number of elements in it takes the same183 * amount of time as keeping a count_ member up to date and getting its value;184 * <li>if getCount is not called, adding and removing elements have no overhead.185 * @return {number} The number of elements in the set.186 */187goog.structs.StringSet.prototype.getCount = function() {188  var count = 0;189  for (var key in this.elements_) {190    if (this.elements_.hasOwnProperty(key)) {191      count++;192    }193  }194  return count;195};196/**197 * Calculates the difference of two sets.198 * @param {!goog.structs.StringSet} stringSet The set to subtract from this set.199 * @return {!goog.structs.StringSet} {@code this} minus {@code stringSet}.200 */201goog.structs.StringSet.prototype.getDifference = function(stringSet) {202  var ret = new goog.structs.StringSet;203  ret.addDifference_(this, stringSet);204  return ret;205};206/**207 * Calculates the intersection of this set with another set.208 * @param {!goog.structs.StringSet} stringSet The set to take the intersection209 *     with.210 * @return {!goog.structs.StringSet} A new set with the common elements.211 */212goog.structs.StringSet.prototype.getIntersection = function(stringSet) {213  var ret = new goog.structs.StringSet;214  for (var key in this.elements_) {215    if (stringSet.elements_.hasOwnProperty(key) &&216        this.elements_.hasOwnProperty(key)) {217      ret.elements_[key] = null;218    }219  }220  return ret;221};222/**223 * Calculates the symmetric difference of two sets.224 * @param {!goog.structs.StringSet} stringSet The other set.225 * @return {!goog.structs.StringSet} A new set with the elements in exactly one226 *     of {@code this} and {@code stringSet}.227 */228goog.structs.StringSet.prototype.getSymmetricDifference = function(stringSet) {229  var ret = new goog.structs.StringSet;230  ret.addDifference_(this, stringSet);231  ret.addDifference_(stringSet, this);232  return ret;233};234/**235 * Calculates the union of this set and another set.236 * @param {!goog.structs.StringSet} stringSet The set to take the union with.237 * @return {!goog.structs.StringSet} A new set with the union of elements.238 */239goog.structs.StringSet.prototype.getUnion = function(stringSet) {240  var ret = this.clone();241  ret.addSet(stringSet);242  return ret;243};244/**245 * @return {!Array.<string>} The elements of the set.246 */247goog.structs.StringSet.prototype.getValues = function() {248  var ret = [];249  for (var key in this.elements_) {250    if (this.elements_.hasOwnProperty(key)) {251      ret.push(this.decode(key));252    }253  }254  return ret;255};256/**257 * Tells if this set and the given set are disjoint.258 * @param {!goog.structs.StringSet} stringSet The other set.259 * @return {boolean} True iff they don't have common elements.260 */261goog.structs.StringSet.prototype.isDisjoint = function(stringSet) {262  for (var key in this.elements_) {263    if (stringSet.elements_.hasOwnProperty(key) &&264        this.elements_.hasOwnProperty(key)) {265      return false;266    }267  }268  return true;269};270/**271 * @return {boolean} Whether the set is empty.272 */273goog.structs.StringSet.prototype.isEmpty = function() {274  for (var key in this.elements_) {275    if (this.elements_.hasOwnProperty(key)) {276      return false;277    }278  }279  return true;280};281/**282 * Tells if this set is the subset of the given set.283 * @param {!goog.structs.StringSet} stringSet The other set.284 * @return {boolean} Whether this set if the subset of that.285 */286goog.structs.StringSet.prototype.isSubsetOf = function(stringSet) {287  for (var key in this.elements_) {288    if (!stringSet.elements_.hasOwnProperty(key) &&289        this.elements_.hasOwnProperty(key)) {290      return false;291    }292  }293  return true;294};295/**296 * Tells if this set is the superset of the given set.297 * @param {!goog.structs.StringSet} stringSet The other set.298 * @return {boolean} Whether this set if the superset of that.299 */300goog.structs.StringSet.prototype.isSupersetOf = function(stringSet) {301  return this.isSubsetOf.call(stringSet, this);302};303/**304 * Removes a single element from the set.305 * @param {*} element The element to remove.306 * @return {boolean} Whether the element was in the set.307 */308goog.structs.StringSet.prototype.remove = function(element) {309  var key = this.encode(element);310  if (this.elements_.hasOwnProperty(key)) {311    delete this.elements_[key];312    return true;313  }314  return false;315};316/**317 * Removes all elements of the given array from this set.318 * @param {!Array} arr The elements to remove.319 */320goog.structs.StringSet.prototype.removeArray = function(arr) {321  for (var i = 0; i < arr.length; i++) {322    delete this.elements_[this.encode(arr[i])];323  }324};325/**326 * Removes all elements of the given set from this set.327 * @param {!goog.structs.StringSet} stringSet The set of elements to remove.328 */329goog.structs.StringSet.prototype.removeSet = function(stringSet) {330  for (var key in stringSet.elements_) {331    delete this.elements_[key];332  }333};334/**335 * Returns an iterator that iterates over the elements in the set.336 * NOTE: creating the iterator copies the whole set so use {@link #forEach} when337 * possible.338 * @param {boolean=} opt_keys Ignored for sets.339 * @return {!goog.iter.Iterator} An iterator over the elements in the set.340 */341goog.structs.StringSet.prototype.__iterator__ = function(opt_keys) {342  return goog.iter.toIterator(this.getValues());...flickr.js
Source:flickr.js  
1// Copyright 2009 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview provides a reusable FlickrSet photo UI component given a public16 * FlickrSetModel.17 *18 * goog.ui.media.FlickrSet is actually a {@link goog.ui.ControlRenderer}, a19 * stateless class - that could/should be used as a Singleton with the static20 * method {@code goog.ui.media.FlickrSet.getInstance} -, that knows how to21 * render Flickr sets. It is designed to be used with a {@link goog.ui.Control},22 * which will actually control the media renderer and provide the23 * {@link goog.ui.Component} base. This design guarantees that all different24 * types of medias will behave alike but will look different.25 *26 * goog.ui.media.FlickrSet expects a {@code goog.ui.media.FlickrSetModel} on27 * {@code goog.ui.Control.getModel} as data models, and renders a flash object28 * that will show the contents of that set.29 *30 * Example of usage:31 *32 * <pre>33 *   var flickrSet = goog.ui.media.FlickrSetModel.newInstance(flickrSetUrl);34 *   goog.ui.media.FlickrSet.newControl(flickrSet).render();35 * </pre>36 *37 * FlickrSet medias currently support the following states:38 *39 * <ul>40 *   <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available'41 *   <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video42 *   <li> {@link goog.ui.Component.State.SELECTED}: flash video is shown43 * </ul>44 *45 * Which can be accessed by46 * <pre>47 *   video.setEnabled(true);48 *   video.setHighlighted(true);49 *   video.setSelected(true);50 * </pre>51 *52 *53 * @supported IE6, FF2+, Safari. Requires flash to actually work.54 *55 * TODO(user): Support non flash users. Maybe show a link to the Flick set,56 * or fetch the data and rendering it using javascript (instead of a broken57 * 'You need to install flash' message).58 */59goog.provide('goog.ui.media.FlickrSet');60goog.provide('goog.ui.media.FlickrSetModel');61goog.require('goog.object');62goog.require('goog.ui.media.FlashObject');63goog.require('goog.ui.media.Media');64goog.require('goog.ui.media.MediaModel');65goog.require('goog.ui.media.MediaModel.Player');66goog.require('goog.ui.media.MediaRenderer');67/**68 * Subclasses a goog.ui.media.MediaRenderer to provide a FlickrSet specific69 * media renderer.70 *71 * This class knows how to parse FlickrSet URLs, and render the DOM structure72 * of flickr set players. This class is meant to be used as a singleton static73 * stateless class, that takes {@code goog.ui.media.Media} instances and renders74 * it. It expects {@code goog.ui.media.Media.getModel} to return a well formed,75 * previously constructed, set id {@see goog.ui.media.FlickrSet.parseUrl},76 * which is the data model this renderer will use to construct the DOM77 * structure. {@see goog.ui.media.FlickrSet.newControl} for a example of78 * constructing a control with this renderer.79 *80 * This design is patterned after81 * http://go/closure_control_subclassing82 *83 * It uses {@link goog.ui.media.FlashObject} to embed the flash object.84 *85 * @constructor86 * @extends {goog.ui.media.MediaRenderer}87 */88goog.ui.media.FlickrSet = function() {89  goog.ui.media.MediaRenderer.call(this);90};91goog.inherits(goog.ui.media.FlickrSet, goog.ui.media.MediaRenderer);92goog.addSingletonGetter(goog.ui.media.FlickrSet);93/**94 * Default CSS class to be applied to the root element of components rendered95 * by this renderer.96 *97 * @type {string}98 */99goog.ui.media.FlickrSet.CSS_CLASS = goog.getCssName('goog-ui-media-flickrset');100/**101 * Flash player URL. Uses Flickr's flash player by default.102 *103 * @type {string}104 * @private105 */106goog.ui.media.FlickrSet.flashUrl_ =107    'http://www.flickr.com/apps/slideshow/show.swf?v=63961';108/**109 * A static convenient method to construct a goog.ui.media.Media control out of110 * a FlickrSet URL. It extracts the set id information on the URL, sets it111 * as the data model goog.ui.media.FlickrSet renderer uses, sets the states112 * supported by the renderer, and returns a Control that binds everything113 * together. This is what you should be using for constructing FlickrSet videos,114 * except if you need more fine control over the configuration.115 *116 * @param {goog.ui.media.FlickrSetModel} dataModel The Flickr Set data model.117 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for118 *     document interaction.119 * @return {goog.ui.media.Media} A Control binded to the FlickrSet renderer.120 * @throws exception in case {@code flickrSetUrl} is an invalid flickr set URL.121 * TODO(user): use {@link goog.ui.media.MediaModel} once it is checked in.122 */123goog.ui.media.FlickrSet.newControl = function(dataModel, opt_domHelper) {124  var control = new goog.ui.media.Media(125      dataModel, goog.ui.media.FlickrSet.getInstance(), opt_domHelper);126  control.setSelected(true);127  return control;128};129/**130 * A static method that sets which flash URL this class should use. Use this if131 * you want to host your own flash flickr player.132 *133 * @param {string} flashUrl The URL of the flash flickr player.134 */135goog.ui.media.FlickrSet.setFlashUrl = function(flashUrl) {136  goog.ui.media.FlickrSet.flashUrl_ = flashUrl;137};138/**139 * Creates the initial DOM structure of the flickr set, which is basically a140 * the flash object pointing to a flickr set player.141 *142 * @param {goog.ui.media.Media} control The media control.143 * @return {Element} The DOM structure that represents this control.144 */145goog.ui.media.FlickrSet.prototype.createDom = function(control) {146  var div = goog.ui.media.FlickrSet.superClass_.createDom.call(this, control);147  var model =148      /** @type {goog.ui.media.FlickrSetModel} */ (control.getDataModel());149  // TODO(user): find out what is the policy about hosting this SWF. figure out150  // if it works over https.151  var flash = new goog.ui.media.FlashObject(152      model.getPlayer().getUrl() || '',153      control.getDomHelper());154  goog.object.forEach(model.getPlayer().getVars(), function(value, key) {155    flash.setFlashVars(key, value);156  });157  flash.render(div);158  return div;159};160/**161 * Returns the CSS class to be applied to the root element of components162 * rendered using this renderer.163 * @return {string} Renderer-specific CSS class.164 */165goog.ui.media.FlickrSet.prototype.getCssClass = function() {166  return goog.ui.media.FlickrSet.CSS_CLASS;167};168/**169 * The {@code goog.ui.media.FlickrAlbum} media data model. It stores a required170 * {@code userId} and {@code setId} fields, sets the flickr Set URL, and171 * allows a few optional parameters.172 *173 * @param {string} userId The flickr userId associated with this set.174 * @param {string} setId The flickr setId associated with this set.175 * @param {string=} opt_caption An optional caption of the flickr set.176 * @param {string=} opt_description An optional description of the flickr set.177 * @constructor178 * @extends {goog.ui.media.MediaModel}179 */180goog.ui.media.FlickrSetModel = function(userId,181                                        setId,182                                        opt_caption,183                                        opt_description) {184  goog.ui.media.MediaModel.call(185      this,186      goog.ui.media.FlickrSetModel.buildUrl(userId, setId),187      opt_caption,188      opt_description,189      goog.ui.media.MediaModel.MimeType.FLASH);190  /**191   * The Flickr user id.192   * @type {string}193   * @private194   */195  this.userId_ = userId;196  /**197   * The Flickr set id.198   * @type {string}199   * @private200   */201  this.setId_ = setId;202  var flashVars = {203    'offsite': 'true',204    'lang': 'en',205    'page_show_url': '/photos/' + userId + '/sets/' + setId + '/show/',206    'page_show_back_url': '/photos/' + userId + '/sets/' + setId,207    'set_id': setId208  };209  var player = new goog.ui.media.MediaModel.Player(210      goog.ui.media.FlickrSet.flashUrl_, flashVars);211  this.setPlayer(player);212};213goog.inherits(goog.ui.media.FlickrSetModel, goog.ui.media.MediaModel);214/**215 * Regular expression used to extract the username and set id out of the flickr216 * URLs.217 *218 * Copied from http://go/markdownlite.js and {@link FlickrExtractor.xml}.219 *220 * @type {RegExp}221 * @private222 * @const223 */224goog.ui.media.FlickrSetModel.MATCHER_ =225    /(?:http:\/\/)?(?:www\.)?flickr\.com\/(?:photos\/([\d\w@\-]+)\/sets\/(\d+))\/?/i;226/**227 * Takes a {@code flickrSetUrl} and extracts the flickr username and set id.228 *229 * @param {string} flickrSetUrl A Flickr set URL.230 * @param {string=} opt_caption An optional caption of the flickr set.231 * @param {string=} opt_description An optional description of the flickr set.232 * @return {goog.ui.media.FlickrSetModel} The data model that represents the233 *     Flickr set.234 * @throws exception in case the parsing fails235 */236goog.ui.media.FlickrSetModel.newInstance = function(flickrSetUrl,237                                                    opt_caption,238                                                    opt_description) {239  if (goog.ui.media.FlickrSetModel.MATCHER_.test(flickrSetUrl)) {240    var data = goog.ui.media.FlickrSetModel.MATCHER_.exec(flickrSetUrl);241    return new goog.ui.media.FlickrSetModel(242        data[1], data[2], opt_caption, opt_description);243  }244  throw Error('failed to parse flickr url: ' + flickrSetUrl);245};246/**247 * Takes a flickr username and set id and returns an URL.248 *249 * @param {string} userId The owner of the set.250 * @param {string} setId The set id.251 * @return {string} The URL of the set.252 */253goog.ui.media.FlickrSetModel.buildUrl = function(userId, setId) {254  return 'http://flickr.com/photos/' + userId + '/sets/' + setId;255};256/**257 * Gets the Flickr user id.258 * @return {string} The Flickr user id.259 */260goog.ui.media.FlickrSetModel.prototype.getUserId = function() {261  return this.userId_;262};263/**264 * Gets the Flickr set id.265 * @return {string} The Flickr set id.266 */267goog.ui.media.FlickrSetModel.prototype.getSetId = function() {268  return this.setId_;...rangeset.js
Source:rangeset.js  
1// Copyright 2009 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview A RangeSet is a structure that manages a list of ranges.16 * Numeric ranges may be added and removed from the RangeSet, and the set may17 * be queried for the presence or absence of individual values or ranges of18 * values.19 *20 * This may be used, for example, to track the availability of sparse elements21 * in an array without iterating over the entire array.22 *23 * @author brenneman@google.com (Shawn Brenneman)24 */25goog.provide('goog.math.RangeSet');26goog.require('goog.array');27goog.require('goog.iter.Iterator');28goog.require('goog.iter.StopIteration');29goog.require('goog.math.Range');30/**31 * Constructs a new RangeSet, which can store numeric ranges.32 *33 * Ranges are treated as half-closed: that is, they are exclusive of their end34 * value [start, end).35 *36 * New ranges added to the set which overlap the values in one or more existing37 * ranges will be merged.38 *39 * @constructor40 */41goog.math.RangeSet = function() {42  /**43   * A sorted list of ranges that represent the values in the set.44   * @type {!Array.<!goog.math.Range>}45   * @private46   */47  this.ranges_ = [];48};49if (goog.DEBUG) {50  /**51   * @return {string} A debug string in the form [[1, 5], [8, 9], [15, 30]].52   * @override53   */54  goog.math.RangeSet.prototype.toString = function() {55    return '[' + this.ranges_.join(', ') + ']';56  };57}58/**59 * Compares two sets for equality.60 *61 * @param {goog.math.RangeSet} a A range set.62 * @param {goog.math.RangeSet} b A range set.63 * @return {boolean} Whether both sets contain the same values.64 */65goog.math.RangeSet.equals = function(a, b) {66  // Fast check for object equality. Also succeeds if a and b are both null.67  return a == b || !!(a && b && goog.array.equals(a.ranges_, b.ranges_,68      goog.math.Range.equals));69};70/**71 * @return {!goog.math.RangeSet} A new RangeSet containing the same values as72 *      this one.73 */74goog.math.RangeSet.prototype.clone = function() {75  var set = new goog.math.RangeSet();76  for (var i = this.ranges_.length; i--;) {77    set.ranges_[i] = this.ranges_[i].clone();78  }79  return set;80};81/**82 * Adds a range to the set. If the new range overlaps existing values, those83 * ranges will be merged.84 *85 * @param {goog.math.Range} a The range to add.86 */87goog.math.RangeSet.prototype.add = function(a) {88  if (a.end <= a.start) {89    // Empty ranges are ignored.90    return;91  }92  a = a.clone();93  // Find the insertion point.94  for (var i = 0, b; b = this.ranges_[i]; i++) {95    if (a.start <= b.end) {96      a.start = Math.min(a.start, b.start);97      break;98    }99  }100  var insertionPoint = i;101  for (; b = this.ranges_[i]; i++) {102    if (a.end < b.start) {103      break;104    }105    a.end = Math.max(a.end, b.end);106  }107  this.ranges_.splice(insertionPoint, i - insertionPoint, a);108};109/**110 * Removes a range of values from the set.111 *112 * @param {goog.math.Range} a The range to remove.113 */114goog.math.RangeSet.prototype.remove = function(a) {115  if (a.end <= a.start) {116    // Empty ranges are ignored.117    return;118  }119  // Find the insertion point.120  for (var i = 0, b; b = this.ranges_[i]; i++) {121    if (a.start < b.end) {122      break;123    }124  }125  if (!b || a.end < b.start) {126    // The range being removed doesn't overlap any existing range. Exit early.127    return;128  }129  var insertionPoint = i;130  if (a.start > b.start) {131    // There is an overlap with the nearest range. Modify it accordingly.132    insertionPoint++;133    if (a.end < b.end) {134      goog.array.insertAt(this.ranges_,135                          new goog.math.Range(a.end, b.end),136                          insertionPoint);137    }138    b.end = a.start;139  }140  for (i = insertionPoint; b = this.ranges_[i]; i++) {141    b.start = Math.max(a.end, b.start);142    if (a.end < b.end) {143      break;144    }145  }146  this.ranges_.splice(insertionPoint, i - insertionPoint);147};148/**149 * Determines whether a given range is in the set. Only succeeds if the entire150 * range is available.151 *152 * @param {goog.math.Range} a The query range.153 * @return {boolean} Whether the entire requested range is set.154 */155goog.math.RangeSet.prototype.contains = function(a) {156  if (a.end <= a.start) {157    return false;158  }159  for (var i = 0, b; b = this.ranges_[i]; i++) {160    if (a.start < b.end) {161      if (a.end >= b.start) {162        return goog.math.Range.contains(b, a);163      }164      break;165    }166  }167  return false;168};169/**170 * Determines whether a given value is set in the RangeSet.171 *172 * @param {number} value The value to test.173 * @return {boolean} Whether the given value is in the set.174 */175goog.math.RangeSet.prototype.containsValue = function(value) {176  for (var i = 0, b; b = this.ranges_[i]; i++) {177    if (value < b.end) {178      if (value >= b.start) {179        return true;180      }181      break;182    }183  }184  return false;185};186/**187 * Returns the union of this RangeSet with another.188 *189 * @param {goog.math.RangeSet} set Another RangeSet.190 * @return {!goog.math.RangeSet} A new RangeSet containing all values from191 *     either set.192 */193goog.math.RangeSet.prototype.union = function(set) {194  // TODO(brenneman): A linear-time merge would be preferable if it is ever a195  // bottleneck.196  set = set.clone();197  for (var i = 0, a; a = this.ranges_[i]; i++) {198    set.add(a);199  }200  return set;201};202/**203 * Subtracts the ranges of another set from this one, returning the result204 * as a new RangeSet.205 *206 * @param {!goog.math.RangeSet} set The RangeSet to subtract.207 * @return {!goog.math.RangeSet} A new RangeSet containing all values in this208 *     set minus the values of the input set.209 */210goog.math.RangeSet.prototype.difference = function(set) {211  var ret = this.clone();212  for (var i = 0, a; a = set.ranges_[i]; i++) {213    ret.remove(a);214  }215  return ret;216};217/**218 * Intersects this RangeSet with another.219 *220 * @param {goog.math.RangeSet} set The RangeSet to intersect with.221 * @return {!goog.math.RangeSet} A new RangeSet containing all values set in222 *     both this and the input set.223 */224goog.math.RangeSet.prototype.intersection = function(set) {225  if (this.isEmpty() || set.isEmpty()) {226    return new goog.math.RangeSet();227  }228  return this.difference(set.inverse(this.getBounds()));229};230/**231 * Creates a subset of this set over the input range.232 *233 * @param {goog.math.Range} range The range to copy into the slice.234 * @return {!goog.math.RangeSet} A new RangeSet with a copy of the values in the235 *     input range.236 */237goog.math.RangeSet.prototype.slice = function(range) {238  var set = new goog.math.RangeSet();239  if (range.start >= range.end) {240    return set;241  }242  for (var i = 0, b; b = this.ranges_[i]; i++) {243    if (b.end <= range.start) {244      continue;245    }246    if (b.start > range.end) {247      break;248    }249    set.add(new goog.math.Range(Math.max(range.start, b.start),250                                Math.min(range.end, b.end)));251  }252  return set;253};254/**255 * Creates an inverted slice of this set over the input range.256 *257 * @param {goog.math.Range} range The range to copy into the slice.258 * @return {!goog.math.RangeSet} A new RangeSet containing inverted values from259 *     the original over the input range.260 */261goog.math.RangeSet.prototype.inverse = function(range) {262  var set = new goog.math.RangeSet();263  set.add(range);264  for (var i = 0, b; b = this.ranges_[i]; i++) {265    if (range.start >= b.end) {266      continue;267    }268    if (range.end < b.start) {269      break;270    }271    set.remove(b);272  }273  return set;274};275/**276 * @return {number} The sum of the lengths of ranges covered in the set.277 */278goog.math.RangeSet.prototype.coveredLength = function() {279  return /** @type {number} */ (goog.array.reduce(280      this.ranges_,281      function(res, range) {282        return res + range.end - range.start;283      }, 0));284};285/**286 * @return {goog.math.Range} The total range this set covers, ignoring any287 *     gaps between ranges.288 */289goog.math.RangeSet.prototype.getBounds = function() {290  if (this.ranges_.length) {291    return new goog.math.Range(this.ranges_[0].start,292                               goog.array.peek(this.ranges_).end);293  }294  return null;295};296/**297 * @return {boolean} Whether any ranges are currently in the set.298 */299goog.math.RangeSet.prototype.isEmpty = function() {300  return this.ranges_.length == 0;301};302/**303 * Removes all values in the set.304 */305goog.math.RangeSet.prototype.clear = function() {306  this.ranges_.length = 0;307};308/**309 * Returns an iterator that iterates over the ranges in the RangeSet.310 *311 * @param {boolean=} opt_keys Ignored for RangeSets.312 * @return {!goog.iter.Iterator} An iterator over the values in the set.313 */314goog.math.RangeSet.prototype.__iterator__ = function(opt_keys) {315  var i = 0;316  var list = this.ranges_;317  var iterator = new goog.iter.Iterator();318  iterator.next = function() {319    if (i >= list.length) {320      throw goog.iter.StopIteration;321    }322    return list[i++].clone();323  };324  return iterator;...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
