mirror of
https://github.com/robertkrimen/otto
synced 2025-10-12 20:27:30 +08:00
Upgrade underscore to 1.4.4, including tests
This commit is contained in:
parent
aaa90bf65c
commit
15aadd333c
12
Makefile
12
Makefile
|
@ -1,4 +1,5 @@
|
||||||
.PHONY: test assets todo fixme otto run test-all release test-synopsis test-i test262
|
.PHONY: test assets todo fixme otto run test-all release test-synopsis test-i test262
|
||||||
|
.PHONY: underscore
|
||||||
|
|
||||||
export TERST_BASE=$(PWD)
|
export TERST_BASE=$(PWD)
|
||||||
|
|
||||||
|
@ -35,6 +36,14 @@ TEST := -v --run Lexer
|
||||||
TEST := -v --run Reflect
|
TEST := -v --run Reflect
|
||||||
TEST := -v --run _reflectSlice
|
TEST := -v --run _reflectSlice
|
||||||
TEST := -v --run _reflect
|
TEST := -v --run _reflect
|
||||||
|
TEST := -v --run _underscore_arrays
|
||||||
|
TEST := -v --run _underscore_chaining
|
||||||
|
TEST := -v --run _underscore_collections
|
||||||
|
TEST := -v --run _underscore_functions
|
||||||
|
TEST := -v --run _underscore_objects
|
||||||
|
TEST := -v --run _underscore_
|
||||||
|
TEST := -v --run _underscore_utility_8\|9
|
||||||
|
TEST := -v --run _underscore_utility
|
||||||
TEST := .
|
TEST := .
|
||||||
|
|
||||||
test: test-i
|
test: test-i
|
||||||
|
@ -70,3 +79,6 @@ test-synopsis: .test test-i otto
|
||||||
|
|
||||||
test262: .test
|
test262: .test
|
||||||
$(MAKE) -C .test/test262 test
|
$(MAKE) -C .test/test262 test
|
||||||
|
|
||||||
|
underscore:
|
||||||
|
$(MAKE) -C $@
|
||||||
|
|
19
otto_test.go
19
otto_test.go
|
@ -10,11 +10,24 @@ import (
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
var testOtto *Otto
|
var (
|
||||||
|
_runTestWithOtto = struct {
|
||||||
|
Otto *Otto
|
||||||
|
test func(string, ...interface{}) Value
|
||||||
|
}{}
|
||||||
|
)
|
||||||
|
|
||||||
|
func failSet(name string, value interface{}) {
|
||||||
|
err := _runTestWithOtto.Otto.Set(name, value)
|
||||||
|
Is(err, nil)
|
||||||
|
if err != nil {
|
||||||
|
Terst().TestingT.FailNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func runTestWithOtto() (*Otto, func(string, ...interface{}) Value) {
|
func runTestWithOtto() (*Otto, func(string, ...interface{}) Value) {
|
||||||
|
cache := &_runTestWithOtto
|
||||||
Otto := New()
|
Otto := New()
|
||||||
testOtto = Otto
|
|
||||||
test := func(name string, expect ...interface{}) Value {
|
test := func(name string, expect ...interface{}) Value {
|
||||||
raise := false
|
raise := false
|
||||||
defer func() {
|
defer func() {
|
||||||
|
@ -48,6 +61,8 @@ func runTestWithOtto() (*Otto, func(string, ...interface{}) Value) {
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
cache.Otto = Otto
|
||||||
|
cache.test = test
|
||||||
return Otto, test
|
return Otto, test
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -8,14 +8,6 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func failSet(name string, value interface{}) {
|
|
||||||
err := testOtto.Set(name, value)
|
|
||||||
Is(err, nil)
|
|
||||||
if err != nil {
|
|
||||||
Terst().TestingT.FailNow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type testStruct struct {
|
type testStruct struct {
|
||||||
Abc bool
|
Abc bool
|
||||||
Def int
|
Def int
|
||||||
|
|
11
underscore/Makefile
Normal file
11
underscore/Makefile
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
.PHONY: source
|
||||||
|
|
||||||
|
source: source.go
|
||||||
|
|
||||||
|
underscore.js:
|
||||||
|
curl -kL http://underscorejs.org/underscore.js > $@
|
||||||
|
|
||||||
|
source.go: underscore.js
|
||||||
|
go-bindata -f underscore -p underscore -u true < $< 2>/dev/null | grep -v '^//' | gofmt > $@
|
||||||
|
head -4 $< >> $@
|
||||||
|
mv $< ..
|
3462
underscore/source.go
Normal file
3462
underscore/source.go
Normal file
File diff suppressed because it is too large
Load Diff
85
underscore/testify
Executable file
85
underscore/testify
Executable file
|
@ -0,0 +1,85 @@
|
||||||
|
#!/usr/bin/env perl
|
||||||
|
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
|
||||||
|
my $underscore_test = shift @ARGV || "";
|
||||||
|
if (!-d $underscore_test) {
|
||||||
|
print <<_END_;
|
||||||
|
Usage:
|
||||||
|
|
||||||
|
testify ./underscore/test
|
||||||
|
|
||||||
|
# Should look something like:
|
||||||
|
arrays.js
|
||||||
|
chaining.js
|
||||||
|
collections.js
|
||||||
|
functions.js
|
||||||
|
index.html
|
||||||
|
objects.js
|
||||||
|
speed.js
|
||||||
|
utility.js
|
||||||
|
vendor
|
||||||
|
|
||||||
|
_END_
|
||||||
|
if ($underscore_test) {
|
||||||
|
die "!: Not a directory: $underscore_test\n"
|
||||||
|
}
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
chdir $underscore_test or die "!: $!";
|
||||||
|
|
||||||
|
my @js = <*.js>;
|
||||||
|
|
||||||
|
for my $file (@js) {
|
||||||
|
open my $fh, '<', $file or die "!: $!";
|
||||||
|
my $tests = join "", <$fh>;
|
||||||
|
my @tests = $tests =~ m/
|
||||||
|
^(\s{2}test\(.*?
|
||||||
|
^\s{2}}\);)$
|
||||||
|
/mgxs;
|
||||||
|
close $fh;
|
||||||
|
next unless @tests;
|
||||||
|
print "$file: ", scalar(@tests), "\n";
|
||||||
|
my $underscore_name = "underscore_$file";
|
||||||
|
$underscore_name =~ s/.js$//;
|
||||||
|
my $go_file = "${underscore_name}_test.go";
|
||||||
|
$go_file =~ s/.js$/.go/;
|
||||||
|
open $fh, '>', $go_file or die "!: $!";
|
||||||
|
|
||||||
|
$fh->print(<<_END_);
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
_END_
|
||||||
|
|
||||||
|
my $count = 0;
|
||||||
|
for my $test (@tests) {
|
||||||
|
$test =~ s/`([^`]+)`/<$1>/g;
|
||||||
|
my ($name) = $test =~ m/^\s*test\(['"]([^'"]+)['"]/;
|
||||||
|
$fh->print(<<_END_);
|
||||||
|
// $name
|
||||||
|
func Test_${underscore_name}_$count(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
$test
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
_END_
|
||||||
|
$count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# test('#779 - delimeters are applied to unescaped text.', 1, function() {
|
||||||
|
# var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
|
||||||
|
# strictEqual(template(), '<<\nx\n>>');
|
||||||
|
# });
|
File diff suppressed because it is too large
Load Diff
346
underscore_arrays_test.go
Normal file
346
underscore_arrays_test.go
Normal file
|
@ -0,0 +1,346 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// first
|
||||||
|
func Test_underscore_arrays_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("first", function() {
|
||||||
|
equal(_.first([1,2,3]), 1, 'can pull out the first element of an array');
|
||||||
|
equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"');
|
||||||
|
equal(_.first([1,2,3], 0).join(', '), "", 'can pass an index to first');
|
||||||
|
equal(_.first([1,2,3], 2).join(', '), '1, 2', 'can pass an index to first');
|
||||||
|
equal(_.first([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to first');
|
||||||
|
var result = (function(){ return _.first(arguments); })(4, 3, 2, 1);
|
||||||
|
equal(result, 4, 'works on an arguments object.');
|
||||||
|
result = _.map([[1,2,3],[1,2,3]], _.first);
|
||||||
|
equal(result.join(','), '1,1', 'works well with _.map');
|
||||||
|
result = (function() { return _.take([1,2,3], 2); })();
|
||||||
|
equal(result.join(','), '1,2', 'aliased as take');
|
||||||
|
|
||||||
|
equal(_.first(null), undefined, 'handles nulls');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rest
|
||||||
|
func Test_underscore_arrays_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("rest", function() {
|
||||||
|
var numbers = [1, 2, 3, 4];
|
||||||
|
equal(_.rest(numbers).join(", "), "2, 3, 4", 'working rest()');
|
||||||
|
equal(_.rest(numbers, 0).join(", "), "1, 2, 3, 4", 'working rest(0)');
|
||||||
|
equal(_.rest(numbers, 2).join(', '), '3, 4', 'rest can take an index');
|
||||||
|
var result = (function(){ return _(arguments).tail(); })(1, 2, 3, 4);
|
||||||
|
equal(result.join(', '), '2, 3, 4', 'aliased as tail and works on arguments object');
|
||||||
|
result = _.map([[1,2,3],[1,2,3]], _.rest);
|
||||||
|
equal(_.flatten(result).join(','), '2,3,2,3', 'works well with _.map');
|
||||||
|
result = (function(){ return _(arguments).drop(); })(1, 2, 3, 4);
|
||||||
|
equal(result.join(', '), '2, 3, 4', 'aliased as drop and works on arguments object');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// initial
|
||||||
|
func Test_underscore_arrays_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("initial", function() {
|
||||||
|
equal(_.initial([1,2,3,4,5]).join(", "), "1, 2, 3, 4", 'working initial()');
|
||||||
|
equal(_.initial([1,2,3,4],2).join(", "), "1, 2", 'initial can take an index');
|
||||||
|
var result = (function(){ return _(arguments).initial(); })(1, 2, 3, 4);
|
||||||
|
equal(result.join(", "), "1, 2, 3", 'initial works on arguments object');
|
||||||
|
result = _.map([[1,2,3],[1,2,3]], _.initial);
|
||||||
|
equal(_.flatten(result).join(','), '1,2,1,2', 'initial works with _.map');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// last
|
||||||
|
func Test_underscore_arrays_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("last", function() {
|
||||||
|
equal(_.last([1,2,3]), 3, 'can pull out the last element of an array');
|
||||||
|
equal(_.last([1,2,3], 0).join(', '), "", 'can pass an index to last');
|
||||||
|
equal(_.last([1,2,3], 2).join(', '), '2, 3', 'can pass an index to last');
|
||||||
|
equal(_.last([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to last');
|
||||||
|
var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4);
|
||||||
|
equal(result, 4, 'works on an arguments object');
|
||||||
|
result = _.map([[1,2,3],[1,2,3]], _.last);
|
||||||
|
equal(result.join(','), '3,3', 'works well with _.map');
|
||||||
|
|
||||||
|
equal(_.last(null), undefined, 'handles nulls');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// compact
|
||||||
|
func Test_underscore_arrays_4(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("compact", function() {
|
||||||
|
equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values');
|
||||||
|
var result = (function(){ return _.compact(arguments).length; })(0, 1, false, 2, false, 3);
|
||||||
|
equal(result, 3, 'works on an arguments object');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// flatten
|
||||||
|
func Test_underscore_arrays_5(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("flatten", function() {
|
||||||
|
var list = [1, [2], [3, [[[4]]]]];
|
||||||
|
deepEqual(_.flatten(list), [1,2,3,4], 'can flatten nested arrays');
|
||||||
|
deepEqual(_.flatten(list, true), [1,2,3,[[[4]]]], 'can shallowly flatten nested arrays');
|
||||||
|
var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]);
|
||||||
|
deepEqual(result, [1,2,3,4], 'works on an arguments object');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// without
|
||||||
|
func Test_underscore_arrays_6(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("without", function() {
|
||||||
|
var list = [1, 2, 1, 0, 3, 1, 4];
|
||||||
|
equal(_.without(list, 0, 1).join(', '), '2, 3, 4', 'can remove all instances of an object');
|
||||||
|
var result = (function(){ return _.without(arguments, 0, 1); })(1, 2, 1, 0, 3, 1, 4);
|
||||||
|
equal(result.join(', '), '2, 3, 4', 'works on an arguments object');
|
||||||
|
|
||||||
|
var list = [{one : 1}, {two : 2}];
|
||||||
|
ok(_.without(list, {one : 1}).length == 2, 'uses real object identity for comparisons.');
|
||||||
|
ok(_.without(list, list[0]).length == 1, 'ditto.');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// uniq
|
||||||
|
func Test_underscore_arrays_7(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("uniq", function() {
|
||||||
|
var list = [1, 2, 1, 3, 1, 4];
|
||||||
|
equal(_.uniq(list).join(', '), '1, 2, 3, 4', 'can find the unique values of an unsorted array');
|
||||||
|
|
||||||
|
var list = [1, 1, 1, 2, 2, 3];
|
||||||
|
equal(_.uniq(list, true).join(', '), '1, 2, 3', 'can find the unique values of a sorted array faster');
|
||||||
|
|
||||||
|
var list = [{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}];
|
||||||
|
var iterator = function(value) { return value.name; };
|
||||||
|
equal(_.map(_.uniq(list, false, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator');
|
||||||
|
|
||||||
|
equal(_.map(_.uniq(list, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');
|
||||||
|
|
||||||
|
var iterator = function(value) { return value +1; };
|
||||||
|
var list = [1, 2, 2, 3, 4, 4];
|
||||||
|
equal(_.uniq(list, true, iterator).join(', '), '1, 2, 3, 4', 'iterator works with sorted array');
|
||||||
|
|
||||||
|
var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
|
||||||
|
equal(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// intersection
|
||||||
|
func Test_underscore_arrays_8(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("intersection", function() {
|
||||||
|
var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho'];
|
||||||
|
equal(_.intersection(stooges, leaders).join(''), 'moe', 'can take the set intersection of two arrays');
|
||||||
|
equal(_(stooges).intersection(leaders).join(''), 'moe', 'can perform an OO-style intersection');
|
||||||
|
var result = (function(){ return _.intersection(arguments, leaders); })('moe', 'curly', 'larry');
|
||||||
|
equal(result.join(''), 'moe', 'works on an arguments object');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// union
|
||||||
|
func Test_underscore_arrays_9(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("union", function() {
|
||||||
|
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
|
||||||
|
equal(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays');
|
||||||
|
|
||||||
|
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
|
||||||
|
equal(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// difference
|
||||||
|
func Test_underscore_arrays_10(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("difference", function() {
|
||||||
|
var result = _.difference([1, 2, 3], [2, 30, 40]);
|
||||||
|
equal(result.join(' '), '1 3', 'takes the difference of two arrays');
|
||||||
|
|
||||||
|
var result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
|
||||||
|
equal(result.join(' '), '3 4', 'takes the difference of three arrays');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// zip
|
||||||
|
func Test_underscore_arrays_11(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('zip', function() {
|
||||||
|
var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true];
|
||||||
|
var stooges = _.zip(names, ages, leaders);
|
||||||
|
equal(String(stooges), 'moe,30,true,larry,40,,curly,50,', 'zipped together arrays of different lengths');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// object
|
||||||
|
func Test_underscore_arrays_12(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('object', function() {
|
||||||
|
var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
|
||||||
|
var shouldBe = {moe: 30, larry: 40, curly: 50};
|
||||||
|
ok(_.isEqual(result, shouldBe), 'two arrays zipped together into an object');
|
||||||
|
|
||||||
|
result = _.object([['one', 1], ['two', 2], ['three', 3]]);
|
||||||
|
shouldBe = {one: 1, two: 2, three: 3};
|
||||||
|
ok(_.isEqual(result, shouldBe), 'an array of pairs zipped together into an object');
|
||||||
|
|
||||||
|
var stooges = {moe: 30, larry: 40, curly: 50};
|
||||||
|
ok(_.isEqual(_.object(_.pairs(stooges)), stooges), 'an object converted to pairs and back to an object');
|
||||||
|
|
||||||
|
ok(_.isEqual(_.object(null), {}), 'handles nulls');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexOf
|
||||||
|
func Test_underscore_arrays_13(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("indexOf", function() {
|
||||||
|
var numbers = [1, 2, 3];
|
||||||
|
numbers.indexOf = null;
|
||||||
|
equal(_.indexOf(numbers, 2), 1, 'can compute indexOf, even without the native function');
|
||||||
|
var result = (function(){ return _.indexOf(arguments, 2); })(1, 2, 3);
|
||||||
|
equal(result, 1, 'works on an arguments object');
|
||||||
|
equal(_.indexOf(null, 2), -1, 'handles nulls properly');
|
||||||
|
|
||||||
|
var numbers = [10, 20, 30, 40, 50], num = 35;
|
||||||
|
var index = _.indexOf(numbers, num, true);
|
||||||
|
equal(index, -1, '35 is not in the list');
|
||||||
|
|
||||||
|
numbers = [10, 20, 30, 40, 50]; num = 40;
|
||||||
|
index = _.indexOf(numbers, num, true);
|
||||||
|
equal(index, 3, '40 is in the list');
|
||||||
|
|
||||||
|
numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40;
|
||||||
|
index = _.indexOf(numbers, num, true);
|
||||||
|
equal(index, 1, '40 is in the list');
|
||||||
|
|
||||||
|
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
|
||||||
|
index = _.indexOf(numbers, 2, 5);
|
||||||
|
equal(index, 7, 'supports the fromIndex argument');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastIndexOf
|
||||||
|
func Test_underscore_arrays_14(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("lastIndexOf", function() {
|
||||||
|
var numbers = [1, 0, 1];
|
||||||
|
equal(_.lastIndexOf(numbers, 1), 2);
|
||||||
|
|
||||||
|
numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0];
|
||||||
|
numbers.lastIndexOf = null;
|
||||||
|
equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function');
|
||||||
|
equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element');
|
||||||
|
var result = (function(){ return _.lastIndexOf(arguments, 1); })(1, 0, 1, 0, 0, 1, 0, 0, 0);
|
||||||
|
equal(result, 5, 'works on an arguments object');
|
||||||
|
equal(_.indexOf(null, 2), -1, 'handles nulls properly');
|
||||||
|
|
||||||
|
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
|
||||||
|
var index = _.lastIndexOf(numbers, 2, 2);
|
||||||
|
equal(index, 1, 'supports the fromIndex argument');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// range
|
||||||
|
func Test_underscore_arrays_15(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("range", function() {
|
||||||
|
equal(_.range(0).join(''), '', 'range with 0 as a first argument generates an empty array');
|
||||||
|
equal(_.range(4).join(' '), '0 1 2 3', 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
|
||||||
|
equal(_.range(5, 8).join(' '), '5 6 7', 'range with two arguments a & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1');
|
||||||
|
equal(_.range(8, 5).join(''), '', 'range with two arguments a & b, b<a generates an empty array');
|
||||||
|
equal(_.range(3, 10, 3).join(' '), '3 6 9', 'range with three arguments a & b & c, c < b-a, a < b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) < c');
|
||||||
|
equal(_.range(3, 10, 15).join(''), '3', 'range with three arguments a & b & c, c > b-a, a < b generates an array with a single element, equal to a');
|
||||||
|
equal(_.range(12, 7, -2).join(' '), '12 10 8', 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
|
||||||
|
equal(_.range(0, -10, -1).join(' '), '0 -1 -2 -3 -4 -5 -6 -7 -8 -9', 'final example in the Python docs');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
97
underscore_chaining_test.go
Normal file
97
underscore_chaining_test.go
Normal file
|
@ -0,0 +1,97 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// map/flatten/reduce
|
||||||
|
func Test_underscore_chaining_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("map/flatten/reduce", function() {
|
||||||
|
var lyrics = [
|
||||||
|
"I'm a lumberjack and I'm okay",
|
||||||
|
"I sleep all night and I work all day",
|
||||||
|
"He's a lumberjack and he's okay",
|
||||||
|
"He sleeps all night and he works all day"
|
||||||
|
];
|
||||||
|
var counts = _(lyrics).chain()
|
||||||
|
.map(function(line) { return line.split(''); })
|
||||||
|
.flatten()
|
||||||
|
.reduce(function(hash, l) {
|
||||||
|
hash[l] = hash[l] || 0;
|
||||||
|
hash[l]++;
|
||||||
|
return hash;
|
||||||
|
}, {}).value();
|
||||||
|
ok(counts['a'] == 16 && counts['e'] == 10, 'counted all the letters in the song');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// select/reject/sortBy
|
||||||
|
func Test_underscore_chaining_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("select/reject/sortBy", function() {
|
||||||
|
var numbers = [1,2,3,4,5,6,7,8,9,10];
|
||||||
|
numbers = _(numbers).chain().select(function(n) {
|
||||||
|
return n % 2 == 0;
|
||||||
|
}).reject(function(n) {
|
||||||
|
return n % 4 == 0;
|
||||||
|
}).sortBy(function(n) {
|
||||||
|
return -n;
|
||||||
|
}).value();
|
||||||
|
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// select/reject/sortBy in functional style
|
||||||
|
func Test_underscore_chaining_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("select/reject/sortBy in functional style", function() {
|
||||||
|
var numbers = [1,2,3,4,5,6,7,8,9,10];
|
||||||
|
numbers = _.chain(numbers).select(function(n) {
|
||||||
|
return n % 2 == 0;
|
||||||
|
}).reject(function(n) {
|
||||||
|
return n % 4 == 0;
|
||||||
|
}).sortBy(function(n) {
|
||||||
|
return -n;
|
||||||
|
}).value();
|
||||||
|
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reverse/concat/unshift/pop/map
|
||||||
|
func Test_underscore_chaining_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("reverse/concat/unshift/pop/map", function() {
|
||||||
|
var numbers = [1,2,3,4,5];
|
||||||
|
numbers = _(numbers).chain()
|
||||||
|
.reverse()
|
||||||
|
.concat([5, 5, 5])
|
||||||
|
.unshift(17)
|
||||||
|
.pop()
|
||||||
|
.map(function(n){ return n * 2; })
|
||||||
|
.value();
|
||||||
|
equal(numbers.join(', '), "34, 10, 8, 6, 4, 2, 10, 10", 'can chain together array functions.');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
694
underscore_collections_test.go
Normal file
694
underscore_collections_test.go
Normal file
|
@ -0,0 +1,694 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// each
|
||||||
|
func Test_underscore_collections_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("each", function() {
|
||||||
|
_.each([1, 2, 3], function(num, i) {
|
||||||
|
equal(num, i + 1, 'each iterators provide value and iteration count');
|
||||||
|
});
|
||||||
|
|
||||||
|
var answers = [];
|
||||||
|
_.each([1, 2, 3], function(num){ answers.push(num * this.multiplier);}, {multiplier : 5});
|
||||||
|
equal(answers.join(', '), '5, 10, 15', 'context object property accessed');
|
||||||
|
|
||||||
|
answers = [];
|
||||||
|
_.forEach([1, 2, 3], function(num){ answers.push(num); });
|
||||||
|
equal(answers.join(', '), '1, 2, 3', 'aliased as "forEach"');
|
||||||
|
|
||||||
|
answers = [];
|
||||||
|
var obj = {one : 1, two : 2, three : 3};
|
||||||
|
obj.constructor.prototype.four = 4;
|
||||||
|
_.each(obj, function(value, key){ answers.push(key); });
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//equal(answers.join(", "), 'one, two, three', 'iterating over objects works, and ignores the object prototype.');
|
||||||
|
delete obj.constructor.prototype.four;
|
||||||
|
|
||||||
|
var answer = null;
|
||||||
|
_.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; });
|
||||||
|
ok(answer, 'can reference the original collection from inside the iterator');
|
||||||
|
|
||||||
|
answers = 0;
|
||||||
|
_.each(null, function(){ ++answers; });
|
||||||
|
equal(answers, 0, 'handles a null properly');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// map
|
||||||
|
func Test_underscore_collections_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('map', function() {
|
||||||
|
var doubled = _.map([1, 2, 3], function(num){ return num * 2; });
|
||||||
|
equal(doubled.join(', '), '2, 4, 6', 'doubled numbers');
|
||||||
|
|
||||||
|
doubled = _.collect([1, 2, 3], function(num){ return num * 2; });
|
||||||
|
equal(doubled.join(', '), '2, 4, 6', 'aliased as "collect"');
|
||||||
|
|
||||||
|
var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3});
|
||||||
|
equal(tripled.join(', '), '3, 6, 9', 'tripled numbers with context');
|
||||||
|
|
||||||
|
var doubled = _([1, 2, 3]).map(function(num){ return num * 2; });
|
||||||
|
equal(doubled.join(', '), '2, 4, 6', 'OO-style doubled numbers');
|
||||||
|
|
||||||
|
//if (document.querySelectorAll) {
|
||||||
|
// var ids = _.map(document.querySelectorAll('#map-test *'), function(n){ return n.id; });
|
||||||
|
// deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on NodeLists.');
|
||||||
|
//}
|
||||||
|
|
||||||
|
//var ids = _.map($('#map-test').children(), function(n){ return n.id; });
|
||||||
|
//deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on jQuery Array-likes.');
|
||||||
|
|
||||||
|
//var ids = _.map(document.images, function(n){ return n.id; });
|
||||||
|
//ok(ids[0] == 'chart_image', 'can use collection methods on HTMLCollections');
|
||||||
|
|
||||||
|
var ifnull = _.map(null, function(){});
|
||||||
|
ok(_.isArray(ifnull) && ifnull.length === 0, 'handles a null properly');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reduce
|
||||||
|
func Test_underscore_collections_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('reduce', function() {
|
||||||
|
var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0);
|
||||||
|
equal(sum, 6, 'can sum up an array');
|
||||||
|
|
||||||
|
var context = {multiplier : 3};
|
||||||
|
sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num * this.multiplier; }, 0, context);
|
||||||
|
equal(sum, 18, 'can reduce with a context object');
|
||||||
|
|
||||||
|
sum = _.inject([1, 2, 3], function(sum, num){ return sum + num; }, 0);
|
||||||
|
equal(sum, 6, 'aliased as "inject"');
|
||||||
|
|
||||||
|
sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0);
|
||||||
|
equal(sum, 6, 'OO-style reduce');
|
||||||
|
|
||||||
|
var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; });
|
||||||
|
equal(sum, 6, 'default initial value');
|
||||||
|
|
||||||
|
var ifnull;
|
||||||
|
try {
|
||||||
|
_.reduce(null, function(){});
|
||||||
|
} catch (ex) {
|
||||||
|
ifnull = ex;
|
||||||
|
}
|
||||||
|
ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
|
||||||
|
|
||||||
|
ok(_.reduce(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
|
||||||
|
equal(_.reduce([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
|
||||||
|
raises(function() { _.reduce([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reduceRight
|
||||||
|
func Test_underscore_collections_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('reduceRight', function() {
|
||||||
|
var list = _.reduceRight(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
|
||||||
|
equal(list, 'bazbarfoo', 'can perform right folds');
|
||||||
|
|
||||||
|
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
|
||||||
|
equal(list, 'bazbarfoo', 'aliased as "foldr"');
|
||||||
|
|
||||||
|
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; });
|
||||||
|
equal(list, 'bazbarfoo', 'default initial value');
|
||||||
|
|
||||||
|
var ifnull;
|
||||||
|
try {
|
||||||
|
_.reduceRight(null, function(){});
|
||||||
|
} catch (ex) {
|
||||||
|
ifnull = ex;
|
||||||
|
}
|
||||||
|
ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
|
||||||
|
|
||||||
|
var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(sum, num){ return sum + num; });
|
||||||
|
equal(sum, 6, 'default initial value on object');
|
||||||
|
|
||||||
|
ok(_.reduceRight(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
|
||||||
|
|
||||||
|
equal(_.reduceRight([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
|
||||||
|
raises(function() { _.reduceRight([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
|
||||||
|
|
||||||
|
// Assert that the correct arguments are being passed.
|
||||||
|
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
return;
|
||||||
|
|
||||||
|
var args,
|
||||||
|
memo = {},
|
||||||
|
object = {a: 1, b: 2},
|
||||||
|
lastKey = _.keys(object).pop();
|
||||||
|
|
||||||
|
var expected = lastKey == 'a'
|
||||||
|
? [memo, 1, 'a', object]
|
||||||
|
: [memo, 2, 'b', object];
|
||||||
|
|
||||||
|
_.reduceRight(object, function() {
|
||||||
|
args || (args = _.toArray(arguments));
|
||||||
|
}, memo);
|
||||||
|
|
||||||
|
deepEqual(args, expected);
|
||||||
|
|
||||||
|
// And again, with numeric keys.
|
||||||
|
|
||||||
|
object = {'2': 'a', '1': 'b'};
|
||||||
|
lastKey = _.keys(object).pop();
|
||||||
|
args = null;
|
||||||
|
|
||||||
|
expected = lastKey == '2'
|
||||||
|
? [memo, 'a', '2', object]
|
||||||
|
: [memo, 'b', '1', object];
|
||||||
|
|
||||||
|
_.reduceRight(object, function() {
|
||||||
|
args || (args = _.toArray(arguments));
|
||||||
|
}, memo);
|
||||||
|
|
||||||
|
deepEqual(args, expected);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// find
|
||||||
|
func Test_underscore_collections_4(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('find', function() {
|
||||||
|
var array = [1, 2, 3, 4];
|
||||||
|
strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found <value>');
|
||||||
|
strictEqual(_.find(array, function() { return false; }), void 0, 'should return <undefined> if <value> is not found');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// detect
|
||||||
|
func Test_underscore_collections_5(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('detect', function() {
|
||||||
|
var result = _.detect([1, 2, 3], function(num){ return num * 2 == 4; });
|
||||||
|
equal(result, 2, 'found the first "2" and broke the loop');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// select
|
||||||
|
func Test_underscore_collections_6(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('select', function() {
|
||||||
|
var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
|
||||||
|
equal(evens.join(', '), '2, 4, 6', 'selected each even number');
|
||||||
|
|
||||||
|
evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
|
||||||
|
equal(evens.join(', '), '2, 4, 6', 'aliased as "filter"');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reject
|
||||||
|
func Test_underscore_collections_7(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('reject', function() {
|
||||||
|
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
|
||||||
|
equal(odds.join(', '), '1, 3, 5', 'rejected each even number');
|
||||||
|
|
||||||
|
var context = "obj";
|
||||||
|
|
||||||
|
var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){
|
||||||
|
equal(context, "obj");
|
||||||
|
return num % 2 != 0;
|
||||||
|
}, context);
|
||||||
|
equal(evens.join(', '), '2, 4, 6', 'rejected each odd number');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// all
|
||||||
|
func Test_underscore_collections_8(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('all', function() {
|
||||||
|
ok(_.all([], _.identity), 'the empty set');
|
||||||
|
ok(_.all([true, true, true], _.identity), 'all true values');
|
||||||
|
ok(!_.all([true, false, true], _.identity), 'one false value');
|
||||||
|
ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');
|
||||||
|
ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');
|
||||||
|
ok(_.all([1], _.identity) === true, 'cast to boolean - true');
|
||||||
|
ok(_.all([0], _.identity) === false, 'cast to boolean - false');
|
||||||
|
ok(_.every([true, true, true], _.identity), 'aliased as "every"');
|
||||||
|
ok(!_.all([undefined, undefined, undefined], _.identity), 'works with arrays of undefined');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// any
|
||||||
|
func Test_underscore_collections_9(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('any', function() {
|
||||||
|
var nativeSome = Array.prototype.some;
|
||||||
|
Array.prototype.some = null;
|
||||||
|
ok(!_.any([]), 'the empty set');
|
||||||
|
ok(!_.any([false, false, false]), 'all false values');
|
||||||
|
ok(_.any([false, false, true]), 'one true value');
|
||||||
|
ok(_.any([null, 0, 'yes', false]), 'a string');
|
||||||
|
ok(!_.any([null, 0, '', false]), 'falsy values');
|
||||||
|
ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');
|
||||||
|
ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');
|
||||||
|
ok(_.any([1], _.identity) === true, 'cast to boolean - true');
|
||||||
|
ok(_.any([0], _.identity) === false, 'cast to boolean - false');
|
||||||
|
ok(_.some([false, false, true]), 'aliased as "some"');
|
||||||
|
Array.prototype.some = nativeSome;
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// include
|
||||||
|
func Test_underscore_collections_10(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('include', function() {
|
||||||
|
ok(_.include([1,2,3], 2), 'two is in the array');
|
||||||
|
ok(!_.include([1,3,9], 2), 'two is not in the array');
|
||||||
|
ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');
|
||||||
|
ok(_([1,2,3]).include(2), 'OO-style include');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// invoke
|
||||||
|
func Test_underscore_collections_11(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('invoke', function() {
|
||||||
|
var list = [[5, 1, 7], [3, 2, 1]];
|
||||||
|
var result = _.invoke(list, 'sort');
|
||||||
|
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
|
||||||
|
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// invoke w/ function reference
|
||||||
|
func Test_underscore_collections_12(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('invoke w/ function reference', function() {
|
||||||
|
var list = [[5, 1, 7], [3, 2, 1]];
|
||||||
|
var result = _.invoke(list, Array.prototype.sort);
|
||||||
|
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
|
||||||
|
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// invoke when strings have a call method
|
||||||
|
func Test_underscore_collections_13(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('invoke when strings have a call method', function() {
|
||||||
|
String.prototype.call = function() {
|
||||||
|
return 42;
|
||||||
|
};
|
||||||
|
var list = [[5, 1, 7], [3, 2, 1]];
|
||||||
|
var s = "foo";
|
||||||
|
equal(s.call(), 42, "call function exists");
|
||||||
|
var result = _.invoke(list, 'sort');
|
||||||
|
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
|
||||||
|
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
|
||||||
|
delete String.prototype.call;
|
||||||
|
equal(s.call, undefined, "call function removed");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pluck
|
||||||
|
func Test_underscore_collections_14(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('pluck', function() {
|
||||||
|
var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
|
||||||
|
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'pulls names out of objects');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// where
|
||||||
|
func Test_underscore_collections_15(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('where', function() {
|
||||||
|
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
|
||||||
|
var result = _.where(list, {a: 1});
|
||||||
|
equal(result.length, 3);
|
||||||
|
equal(result[result.length - 1].b, 4);
|
||||||
|
result = _.where(list, {b: 2});
|
||||||
|
equal(result.length, 2);
|
||||||
|
equal(result[0].a, 1);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// findWhere
|
||||||
|
func Test_underscore_collections_16(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('findWhere', function() {
|
||||||
|
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}];
|
||||||
|
var result = _.findWhere(list, {a: 1});
|
||||||
|
deepEqual(result, {a: 1, b: 2});
|
||||||
|
result = _.findWhere(list, {b: 4});
|
||||||
|
deepEqual(result, {a: 1, b: 4});
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// max
|
||||||
|
func Test_underscore_collections_17(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('max', function() {
|
||||||
|
equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max');
|
||||||
|
|
||||||
|
var neg = _.max([1, 2, 3], function(num){ return -num; });
|
||||||
|
equal(neg, 1, 'can perform a computation-based max');
|
||||||
|
|
||||||
|
equal(-Infinity, _.max({}), 'Maximum value of an empty object');
|
||||||
|
equal(-Infinity, _.max([]), 'Maximum value of an empty array');
|
||||||
|
equal(_.max({'a': 'a'}), -Infinity, 'Maximum value of a non-numeric collection');
|
||||||
|
|
||||||
|
//equal(299999, _.max(_.range(1,300000)), "Maximum value of a too-big array");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// min
|
||||||
|
func Test_underscore_collections_18(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('min', function() {
|
||||||
|
equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min');
|
||||||
|
|
||||||
|
var neg = _.min([1, 2, 3], function(num){ return -num; });
|
||||||
|
equal(neg, 3, 'can perform a computation-based min');
|
||||||
|
|
||||||
|
equal(Infinity, _.min({}), 'Minimum value of an empty object');
|
||||||
|
equal(Infinity, _.min([]), 'Minimum value of an empty array');
|
||||||
|
equal(_.min({'a': 'a'}), Infinity, 'Minimum value of a non-numeric collection');
|
||||||
|
|
||||||
|
var now = new Date(9999999999);
|
||||||
|
var then = new Date(0);
|
||||||
|
equal(_.min([now, then]), then);
|
||||||
|
|
||||||
|
//equal(1, _.min(_.range(1,300000)), "Minimum value of a too-big array");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sortBy
|
||||||
|
func Test_underscore_collections_19(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('sortBy', function() {
|
||||||
|
var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}];
|
||||||
|
people = _.sortBy(people, function(person){ return person.age; });
|
||||||
|
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'stooges sorted by age');
|
||||||
|
|
||||||
|
var list = [undefined, 4, 1, undefined, 3, 2];
|
||||||
|
equal(_.sortBy(list, _.identity).join(','), '1,2,3,4,,', 'sortBy with undefined values');
|
||||||
|
|
||||||
|
var list = ["one", "two", "three", "four", "five"];
|
||||||
|
var sorted = _.sortBy(list, 'length');
|
||||||
|
equal(sorted.join(' '), 'one two four five three', 'sorted by length');
|
||||||
|
|
||||||
|
function Pair(x, y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
var collection = [
|
||||||
|
new Pair(1, 1), new Pair(1, 2),
|
||||||
|
new Pair(1, 3), new Pair(1, 4),
|
||||||
|
new Pair(1, 5), new Pair(1, 6),
|
||||||
|
new Pair(2, 1), new Pair(2, 2),
|
||||||
|
new Pair(2, 3), new Pair(2, 4),
|
||||||
|
new Pair(2, 5), new Pair(2, 6),
|
||||||
|
new Pair(undefined, 1), new Pair(undefined, 2),
|
||||||
|
new Pair(undefined, 3), new Pair(undefined, 4),
|
||||||
|
new Pair(undefined, 5), new Pair(undefined, 6)
|
||||||
|
];
|
||||||
|
|
||||||
|
var actual = _.sortBy(collection, function(pair) {
|
||||||
|
return pair.x;
|
||||||
|
});
|
||||||
|
|
||||||
|
deepEqual(actual, collection, 'sortBy should be stable');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// groupBy
|
||||||
|
func Test_underscore_collections_20(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('groupBy', function() {
|
||||||
|
var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });
|
||||||
|
ok('0' in parity && '1' in parity, 'created a group for each value');
|
||||||
|
equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');
|
||||||
|
|
||||||
|
var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
|
||||||
|
var grouped = _.groupBy(list, 'length');
|
||||||
|
equal(grouped['3'].join(' '), 'one two six ten');
|
||||||
|
equal(grouped['4'].join(' '), 'four five nine');
|
||||||
|
equal(grouped['5'].join(' '), 'three seven eight');
|
||||||
|
|
||||||
|
var context = {};
|
||||||
|
_.groupBy([{}], function(){ ok(this === context); }, context);
|
||||||
|
|
||||||
|
grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {
|
||||||
|
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
|
||||||
|
});
|
||||||
|
equal(grouped.constructor.length, 1);
|
||||||
|
equal(grouped.hasOwnProperty.length, 2);
|
||||||
|
|
||||||
|
var array = [{}];
|
||||||
|
_.groupBy(array, function(value, index, obj){ ok(obj === array); });
|
||||||
|
|
||||||
|
var array = [1, 2, 1, 2, 3];
|
||||||
|
var grouped = _.groupBy(array);
|
||||||
|
equal(grouped['1'].length, 2);
|
||||||
|
equal(grouped['3'].length, 1);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// countBy
|
||||||
|
func Test_underscore_collections_21(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('countBy', function() {
|
||||||
|
var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });
|
||||||
|
equal(parity['true'], 2);
|
||||||
|
equal(parity['false'], 3);
|
||||||
|
|
||||||
|
var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
|
||||||
|
var grouped = _.countBy(list, 'length');
|
||||||
|
equal(grouped['3'], 4);
|
||||||
|
equal(grouped['4'], 3);
|
||||||
|
equal(grouped['5'], 3);
|
||||||
|
|
||||||
|
var context = {};
|
||||||
|
_.countBy([{}], function(){ ok(this === context); }, context);
|
||||||
|
|
||||||
|
grouped = _.countBy([4.2, 6.1, 6.4], function(num) {
|
||||||
|
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
|
||||||
|
});
|
||||||
|
equal(grouped.constructor, 1);
|
||||||
|
equal(grouped.hasOwnProperty, 2);
|
||||||
|
|
||||||
|
var array = [{}];
|
||||||
|
_.countBy(array, function(value, index, obj){ ok(obj === array); });
|
||||||
|
|
||||||
|
var array = [1, 2, 1, 2, 3];
|
||||||
|
var grouped = _.countBy(array);
|
||||||
|
equal(grouped['1'], 2);
|
||||||
|
equal(grouped['3'], 1);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sortedIndex
|
||||||
|
func Test_underscore_collections_22(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('sortedIndex', function() {
|
||||||
|
var numbers = [10, 20, 30, 40, 50], num = 35;
|
||||||
|
var indexForNum = _.sortedIndex(numbers, num);
|
||||||
|
equal(indexForNum, 3, '35 should be inserted at index 3');
|
||||||
|
|
||||||
|
var indexFor30 = _.sortedIndex(numbers, 30);
|
||||||
|
equal(indexFor30, 2, '30 should be inserted at index 2');
|
||||||
|
|
||||||
|
var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];
|
||||||
|
var iterator = function(obj){ return obj.x; };
|
||||||
|
strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);
|
||||||
|
strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);
|
||||||
|
|
||||||
|
var context = {1: 2, 2: 3, 3: 4};
|
||||||
|
iterator = function(obj){ return this[obj]; };
|
||||||
|
strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// shuffle
|
||||||
|
func Test_underscore_collections_23(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('shuffle', function() {
|
||||||
|
var numbers = _.range(10);
|
||||||
|
var shuffled = _.shuffle(numbers).sort();
|
||||||
|
notStrictEqual(numbers, shuffled, 'original object is unmodified');
|
||||||
|
equal(shuffled.join(','), numbers.join(','), 'contains the same members before and after shuffle');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// toArray
|
||||||
|
func Test_underscore_collections_24(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('toArray', function() {
|
||||||
|
ok(!_.isArray(arguments), 'arguments object is not an array');
|
||||||
|
ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array');
|
||||||
|
var a = [1,2,3];
|
||||||
|
ok(_.toArray(a) !== a, 'array is cloned');
|
||||||
|
equal(_.toArray(a).join(', '), '1, 2, 3', 'cloned array contains same elements');
|
||||||
|
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
return;
|
||||||
|
|
||||||
|
var numbers = _.toArray({one : 1, two : 2, three : 3});
|
||||||
|
equal(numbers.join(', '), '1, 2, 3', 'object flattened into array');
|
||||||
|
|
||||||
|
// test in IE < 9
|
||||||
|
try {
|
||||||
|
var actual = _.toArray(document.childNodes);
|
||||||
|
} catch(ex) { }
|
||||||
|
|
||||||
|
ok(_.isArray(actual), 'should not throw converting a node list');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// size
|
||||||
|
func Test_underscore_collections_25(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('size', function() {
|
||||||
|
equal(_.size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object');
|
||||||
|
equal(_.size([1, 2, 3]), 3, 'can compute the size of an array');
|
||||||
|
|
||||||
|
var func = function() {
|
||||||
|
return _.size(arguments);
|
||||||
|
};
|
||||||
|
|
||||||
|
equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object');
|
||||||
|
|
||||||
|
equal(_.size('hello'), 5, 'can compute the size of a string');
|
||||||
|
|
||||||
|
equal(_.size(null), 0, 'handles nulls');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
213
underscore_functions_test.go
Normal file
213
underscore_functions_test.go
Normal file
|
@ -0,0 +1,213 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bind
|
||||||
|
func Test_underscore_functions_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("bind", function() {
|
||||||
|
var context = {name : 'moe'};
|
||||||
|
var func = function(arg) { return "name: " + (this.name || arg); };
|
||||||
|
var bound = _.bind(func, context);
|
||||||
|
equal(bound(), 'name: moe', 'can bind a function to a context');
|
||||||
|
|
||||||
|
bound = _(func).bind(context);
|
||||||
|
equal(bound(), 'name: moe', 'can do OO-style binding');
|
||||||
|
|
||||||
|
bound = _.bind(func, null, 'curly');
|
||||||
|
equal(bound(), 'name: curly', 'can bind without specifying a context');
|
||||||
|
|
||||||
|
func = function(salutation, name) { return salutation + ': ' + name; };
|
||||||
|
func = _.bind(func, this, 'hello');
|
||||||
|
equal(func('moe'), 'hello: moe', 'the function was partially applied in advance');
|
||||||
|
|
||||||
|
func = _.bind(func, this, 'curly');
|
||||||
|
equal(func(), 'hello: curly', 'the function was completely applied in advance');
|
||||||
|
|
||||||
|
func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname; };
|
||||||
|
func = _.bind(func, this, 'hello', 'moe', 'curly');
|
||||||
|
equal(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments');
|
||||||
|
|
||||||
|
func = function(context, message) { equal(this, context, message); };
|
||||||
|
_.bind(func, 0, 0, 'can bind a function to <0>')();
|
||||||
|
_.bind(func, '', '', 'can bind a function to an empty string')();
|
||||||
|
_.bind(func, false, false, 'can bind a function to <false>')();
|
||||||
|
|
||||||
|
// These tests are only meaningful when using a browser without a native bind function
|
||||||
|
// To test this with a modern browser, set underscore's nativeBind to undefined
|
||||||
|
var F = function () { return this; };
|
||||||
|
var Boundf = _.bind(F, {hello: "moe curly"});
|
||||||
|
equal(Boundf().hello, "moe curly", "When called without the new operator, it's OK to be bound to the context");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// partial
|
||||||
|
func Test_underscore_functions_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("partial", function() {
|
||||||
|
var obj = {name: 'moe'};
|
||||||
|
var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); };
|
||||||
|
|
||||||
|
obj.func = _.partial(func, 'a', 'b');
|
||||||
|
equal(obj.func('c', 'd'), 'moe a b c d', 'can partially apply');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bindAll
|
||||||
|
func Test_underscore_functions_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("bindAll", function() {
|
||||||
|
var curly = {name : 'curly'}, moe = {
|
||||||
|
name : 'moe',
|
||||||
|
getName : function() { return 'name: ' + this.name; },
|
||||||
|
sayHi : function() { return 'hi: ' + this.name; }
|
||||||
|
};
|
||||||
|
curly.getName = moe.getName;
|
||||||
|
_.bindAll(moe, 'getName', 'sayHi');
|
||||||
|
curly.sayHi = moe.sayHi;
|
||||||
|
equal(curly.getName(), 'name: curly', 'unbound function is bound to current object');
|
||||||
|
equal(curly.sayHi(), 'hi: moe', 'bound function is still bound to original object');
|
||||||
|
|
||||||
|
curly = {name : 'curly'};
|
||||||
|
moe = {
|
||||||
|
name : 'moe',
|
||||||
|
getName : function() { return 'name: ' + this.name; },
|
||||||
|
sayHi : function() { return 'hi: ' + this.name; }
|
||||||
|
};
|
||||||
|
|
||||||
|
// FIXME: This functionality is being changed in the underscore master right now
|
||||||
|
//raises(function() { _.bindAll(moe); }, Error, 'throws an error for bindAll with no functions named');
|
||||||
|
|
||||||
|
_.bindAll(moe, 'sayHi');
|
||||||
|
curly.sayHi = moe.sayHi;
|
||||||
|
equal(curly.sayHi(), 'hi: moe');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// memoize
|
||||||
|
func Test_underscore_functions_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("memoize", function() {
|
||||||
|
var fib = function(n) {
|
||||||
|
return n < 2 ? n : fib(n - 1) + fib(n - 2);
|
||||||
|
};
|
||||||
|
var fastFib = _.memoize(fib);
|
||||||
|
equal(fib(10), 55, 'a memoized version of fibonacci produces identical results');
|
||||||
|
equal(fastFib(10), 55, 'a memoized version of fibonacci produces identical results');
|
||||||
|
|
||||||
|
var o = function(str) {
|
||||||
|
return str;
|
||||||
|
};
|
||||||
|
var fastO = _.memoize(o);
|
||||||
|
equal(o('toString'), 'toString', 'checks hasOwnProperty');
|
||||||
|
equal(fastO('toString'), 'toString', 'checks hasOwnProperty');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// once
|
||||||
|
func Test_underscore_functions_4(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("once", function() {
|
||||||
|
var num = 0;
|
||||||
|
var increment = _.once(function(){ num++; });
|
||||||
|
increment();
|
||||||
|
increment();
|
||||||
|
equal(num, 1);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrap
|
||||||
|
func Test_underscore_functions_5(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("wrap", function() {
|
||||||
|
var greet = function(name){ return "hi: " + name; };
|
||||||
|
var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); });
|
||||||
|
equal(backwards('moe'), 'hi: moe eom', 'wrapped the saluation function');
|
||||||
|
|
||||||
|
var inner = function(){ return "Hello "; };
|
||||||
|
var obj = {name : "Moe"};
|
||||||
|
obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; });
|
||||||
|
equal(obj.hi(), "Hello Moe");
|
||||||
|
|
||||||
|
var noop = function(){};
|
||||||
|
var wrapped = _.wrap(noop, function(fn){ return Array.prototype.slice.call(arguments, 0); });
|
||||||
|
var ret = wrapped(['whats', 'your'], 'vector', 'victor');
|
||||||
|
deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// compose
|
||||||
|
func Test_underscore_functions_6(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("compose", function() {
|
||||||
|
var greet = function(name){ return "hi: " + name; };
|
||||||
|
var exclaim = function(sentence){ return sentence + '!'; };
|
||||||
|
var composed = _.compose(exclaim, greet);
|
||||||
|
equal(composed('moe'), 'hi: moe!', 'can compose a function that takes another');
|
||||||
|
|
||||||
|
composed = _.compose(greet, exclaim);
|
||||||
|
equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// after
|
||||||
|
func Test_underscore_functions_7(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("after", function() {
|
||||||
|
var testAfter = function(afterAmount, timesCalled) {
|
||||||
|
var afterCalled = 0;
|
||||||
|
var after = _.after(afterAmount, function() {
|
||||||
|
afterCalled++;
|
||||||
|
});
|
||||||
|
while (timesCalled--) after();
|
||||||
|
return afterCalled;
|
||||||
|
};
|
||||||
|
|
||||||
|
equal(testAfter(5, 5), 1, "after(N) should fire after being called N times");
|
||||||
|
equal(testAfter(5, 4), 0, "after(N) should not fire unless called N times");
|
||||||
|
equal(testAfter(0, 0), 1, "after(0) should fire immediately");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
779
underscore_objects_test.go
Normal file
779
underscore_objects_test.go
Normal file
|
@ -0,0 +1,779 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// keys
|
||||||
|
func Test_underscore_objects_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("keys", function() {
|
||||||
|
equal(_.keys({one : 1, two : 2}).sort().join(', '), 'one, two', 'can extract the keys from an object');
|
||||||
|
// the test above is not safe because it relies on for-in enumeration order
|
||||||
|
var a = []; a[1] = 0;
|
||||||
|
equal(_.keys(a).join(', '), '1', 'is not fooled by sparse arrays; see issue #95');
|
||||||
|
raises(function() { _.keys(null); }, TypeError, 'throws an error for <null> values');
|
||||||
|
raises(function() { _.keys(void 0); }, TypeError, 'throws an error for <undefined> values');
|
||||||
|
raises(function() { _.keys(1); }, TypeError, 'throws an error for number primitives');
|
||||||
|
raises(function() { _.keys('a'); }, TypeError, 'throws an error for string primitives');
|
||||||
|
raises(function() { _.keys(true); }, TypeError, 'throws an error for boolean primitives');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// values
|
||||||
|
func Test_underscore_objects_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("values", function() {
|
||||||
|
equal(_.values({one: 1, two: 2}).sort().join(', '), '1, 2', 'can extract the values from an object');
|
||||||
|
equal(_.values({one: 1, two: 2, length: 3}).sort().join(', '), '1, 2, 3', '... even when one of them is "length"');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pairs
|
||||||
|
func Test_underscore_objects_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("pairs", function() {
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
return;
|
||||||
|
deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs');
|
||||||
|
deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// invert
|
||||||
|
func Test_underscore_objects_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("invert", function() {
|
||||||
|
var obj = {first: 'Moe', second: 'Larry', third: 'Curly'};
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//equal(_.keys(_.invert(obj)).join(' '), 'Moe Larry Curly', 'can invert an object');
|
||||||
|
ok(_.isEqual(_.invert(_.invert(obj)), obj), 'two inverts gets you back where you started');
|
||||||
|
|
||||||
|
var obj = {length: 3};
|
||||||
|
ok(_.invert(obj)['3'] == 'length', 'can invert an object with "length"')
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// functions
|
||||||
|
func Test_underscore_objects_4(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("functions", function() {
|
||||||
|
var obj = {a : 'dash', b : _.map, c : (/yo/), d : _.reduce};
|
||||||
|
ok(_.isEqual(['b', 'd'], _.functions(obj)), 'can grab the function names of any passed-in object');
|
||||||
|
|
||||||
|
var Animal = function(){};
|
||||||
|
Animal.prototype.run = function(){};
|
||||||
|
equal(_.functions(new Animal).join(''), 'run', 'also looks up functions on the prototype');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// extend
|
||||||
|
func Test_underscore_objects_5(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("extend", function() {
|
||||||
|
var result;
|
||||||
|
equal(_.extend({}, {a:'b'}).a, 'b', 'can extend an object with the attributes of another');
|
||||||
|
equal(_.extend({a:'x'}, {a:'b'}).a, 'b', 'properties in source override destination');
|
||||||
|
equal(_.extend({x:'x'}, {a:'b'}).x, 'x', 'properties not in source dont get overriden');
|
||||||
|
result = _.extend({x:'x'}, {a:'a'}, {b:'b'});
|
||||||
|
ok(_.isEqual(result, {x:'x', a:'a', b:'b'}), 'can extend from multiple source objects');
|
||||||
|
result = _.extend({x:'x'}, {a:'a', x:2}, {a:'b'});
|
||||||
|
ok(_.isEqual(result, {x:2, a:'b'}), 'extending from multiple source objects last property trumps');
|
||||||
|
result = _.extend({}, {a: void 0, b: null});
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//equal(_.keys(result).join(''), 'ab', 'extend does not copy undefined values');
|
||||||
|
|
||||||
|
try {
|
||||||
|
result = {};
|
||||||
|
_.extend(result, null, undefined, {a:1});
|
||||||
|
} catch(ex) {}
|
||||||
|
|
||||||
|
equal(result.a, 1, 'should not error on <null> or <undefined> sources');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pick
|
||||||
|
func Test_underscore_objects_6(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("pick", function() {
|
||||||
|
var result;
|
||||||
|
result = _.pick({a:1, b:2, c:3}, 'a', 'c');
|
||||||
|
ok(_.isEqual(result, {a:1, c:3}), 'can restrict properties to those named');
|
||||||
|
result = _.pick({a:1, b:2, c:3}, ['b', 'c']);
|
||||||
|
ok(_.isEqual(result, {b:2, c:3}), 'can restrict properties to those named in an array');
|
||||||
|
result = _.pick({a:1, b:2, c:3}, ['a'], 'b');
|
||||||
|
ok(_.isEqual(result, {a:1, b:2}), 'can restrict properties to those named in mixed args');
|
||||||
|
|
||||||
|
var Obj = function(){};
|
||||||
|
Obj.prototype = {a: 1, b: 2, c: 3};
|
||||||
|
ok(_.isEqual(_.pick(new Obj, 'a', 'c'), {a:1, c: 3}), 'include prototype props');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// omit
|
||||||
|
func Test_underscore_objects_7(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("omit", function() {
|
||||||
|
var result;
|
||||||
|
result = _.omit({a:1, b:2, c:3}, 'b');
|
||||||
|
ok(_.isEqual(result, {a:1, c:3}), 'can omit a single named property');
|
||||||
|
result = _.omit({a:1, b:2, c:3}, 'a', 'c');
|
||||||
|
ok(_.isEqual(result, {b:2}), 'can omit several named properties');
|
||||||
|
result = _.omit({a:1, b:2, c:3}, ['b', 'c']);
|
||||||
|
ok(_.isEqual(result, {a:1}), 'can omit properties named in an array');
|
||||||
|
|
||||||
|
var Obj = function(){};
|
||||||
|
Obj.prototype = {a: 1, b: 2, c: 3};
|
||||||
|
ok(_.isEqual(_.omit(new Obj, 'b'), {a:1, c: 3}), 'include prototype props');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaults
|
||||||
|
func Test_underscore_objects_8(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("defaults", function() {
|
||||||
|
var result;
|
||||||
|
var options = {zero: 0, one: 1, empty: "", nan: NaN, string: "string"};
|
||||||
|
|
||||||
|
_.defaults(options, {zero: 1, one: 10, twenty: 20});
|
||||||
|
equal(options.zero, 0, 'value exists');
|
||||||
|
equal(options.one, 1, 'value exists');
|
||||||
|
equal(options.twenty, 20, 'default applied');
|
||||||
|
|
||||||
|
_.defaults(options, {empty: "full"}, {nan: "nan"}, {word: "word"}, {word: "dog"});
|
||||||
|
equal(options.empty, "", 'value exists');
|
||||||
|
ok(_.isNaN(options.nan), "NaN isn't overridden");
|
||||||
|
equal(options.word, "word", 'new value is added, first one wins');
|
||||||
|
|
||||||
|
try {
|
||||||
|
options = {};
|
||||||
|
_.defaults(options, null, undefined, {a:1});
|
||||||
|
} catch(ex) {}
|
||||||
|
|
||||||
|
equal(options.a, 1, 'should not error on <null> or <undefined> sources');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// clone
|
||||||
|
func Test_underscore_objects_9(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("clone", function() {
|
||||||
|
var moe = {name : 'moe', lucky : [13, 27, 34]};
|
||||||
|
var clone = _.clone(moe);
|
||||||
|
equal(clone.name, 'moe', 'the clone as the attributes of the original');
|
||||||
|
|
||||||
|
clone.name = 'curly';
|
||||||
|
ok(clone.name == 'curly' && moe.name == 'moe', 'clones can change shallow attributes without affecting the original');
|
||||||
|
|
||||||
|
clone.lucky.push(101);
|
||||||
|
equal(_.last(moe.lucky), 101, 'changes to deep attributes are shared with the original');
|
||||||
|
|
||||||
|
equal(_.clone(undefined), void 0, 'non objects should not be changed by clone');
|
||||||
|
equal(_.clone(1), 1, 'non objects should not be changed by clone');
|
||||||
|
equal(_.clone(null), null, 'non objects should not be changed by clone');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isEqual
|
||||||
|
func Test_underscore_objects_10(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isEqual", function() {
|
||||||
|
function First() {
|
||||||
|
this.value = 1;
|
||||||
|
}
|
||||||
|
First.prototype.value = 1;
|
||||||
|
function Second() {
|
||||||
|
this.value = 1;
|
||||||
|
}
|
||||||
|
Second.prototype.value = 2;
|
||||||
|
|
||||||
|
// Basic equality and identity comparisons.
|
||||||
|
ok(_.isEqual(null, null), "<null> is equal to <null>");
|
||||||
|
ok(_.isEqual(), "<undefined> is equal to <undefined>");
|
||||||
|
|
||||||
|
ok(!_.isEqual(0, -0), "<0> is not equal to <-0>");
|
||||||
|
ok(!_.isEqual(-0, 0), "Commutative equality is implemented for <0> and <-0>");
|
||||||
|
ok(!_.isEqual(null, undefined), "<null> is not equal to <undefined>");
|
||||||
|
ok(!_.isEqual(undefined, null), "Commutative equality is implemented for <null> and <undefined>");
|
||||||
|
|
||||||
|
// String object and primitive comparisons.
|
||||||
|
ok(_.isEqual("Curly", "Curly"), "Identical string primitives are equal");
|
||||||
|
ok(_.isEqual(new String("Curly"), new String("Curly")), "String objects with identical primitive values are equal");
|
||||||
|
ok(_.isEqual(new String("Curly"), "Curly"), "String primitives and their corresponding object wrappers are equal");
|
||||||
|
ok(_.isEqual("Curly", new String("Curly")), "Commutative equality is implemented for string objects and primitives");
|
||||||
|
|
||||||
|
ok(!_.isEqual("Curly", "Larry"), "String primitives with different values are not equal");
|
||||||
|
ok(!_.isEqual(new String("Curly"), new String("Larry")), "String objects with different primitive values are not equal");
|
||||||
|
ok(!_.isEqual(new String("Curly"), {toString: function(){ return "Curly"; }}), "String objects and objects with a custom <toString> method are not equal");
|
||||||
|
|
||||||
|
// Number object and primitive comparisons.
|
||||||
|
ok(_.isEqual(75, 75), "Identical number primitives are equal");
|
||||||
|
ok(_.isEqual(new Number(75), new Number(75)), "Number objects with identical primitive values are equal");
|
||||||
|
ok(_.isEqual(75, new Number(75)), "Number primitives and their corresponding object wrappers are equal");
|
||||||
|
ok(_.isEqual(new Number(75), 75), "Commutative equality is implemented for number objects and primitives");
|
||||||
|
ok(!_.isEqual(new Number(0), -0), "<new Number(0)> and <-0> are not equal");
|
||||||
|
ok(!_.isEqual(0, new Number(-0)), "Commutative equality is implemented for <new Number(0)> and <-0>");
|
||||||
|
|
||||||
|
ok(!_.isEqual(new Number(75), new Number(63)), "Number objects with different primitive values are not equal");
|
||||||
|
ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), "Number objects and objects with a <valueOf> method are not equal");
|
||||||
|
|
||||||
|
// Comparisons involving <NaN>.
|
||||||
|
ok(_.isEqual(NaN, NaN), "<NaN> is equal to <NaN>");
|
||||||
|
ok(!_.isEqual(61, NaN), "A number primitive is not equal to <NaN>");
|
||||||
|
ok(!_.isEqual(new Number(79), NaN), "A number object is not equal to <NaN>");
|
||||||
|
ok(!_.isEqual(Infinity, NaN), "<Infinity> is not equal to <NaN>");
|
||||||
|
|
||||||
|
// Boolean object and primitive comparisons.
|
||||||
|
ok(_.isEqual(true, true), "Identical boolean primitives are equal");
|
||||||
|
ok(_.isEqual(new Boolean, new Boolean), "Boolean objects with identical primitive values are equal");
|
||||||
|
ok(_.isEqual(true, new Boolean(true)), "Boolean primitives and their corresponding object wrappers are equal");
|
||||||
|
ok(_.isEqual(new Boolean(true), true), "Commutative equality is implemented for booleans");
|
||||||
|
ok(!_.isEqual(new Boolean(true), new Boolean), "Boolean objects with different primitive values are not equal");
|
||||||
|
|
||||||
|
// Common type coercions.
|
||||||
|
ok(!_.isEqual(true, new Boolean(false)), "Boolean objects are not equal to the boolean primitive <true>");
|
||||||
|
ok(!_.isEqual("75", 75), "String and number primitives with like values are not equal");
|
||||||
|
ok(!_.isEqual(new Number(63), new String(63)), "String and number objects with like values are not equal");
|
||||||
|
ok(!_.isEqual(75, "75"), "Commutative equality is implemented for like string and number values");
|
||||||
|
ok(!_.isEqual(0, ""), "Number and string primitives with like values are not equal");
|
||||||
|
ok(!_.isEqual(1, true), "Number and boolean primitives with like values are not equal");
|
||||||
|
ok(!_.isEqual(new Boolean(false), new Number(0)), "Boolean and number objects with like values are not equal");
|
||||||
|
ok(!_.isEqual(false, new String("")), "Boolean primitives and string objects with like values are not equal");
|
||||||
|
ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), "Dates and their corresponding numeric primitive values are not equal");
|
||||||
|
|
||||||
|
// Dates.
|
||||||
|
ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), "Date objects referencing identical times are equal");
|
||||||
|
ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), "Date objects referencing different times are not equal");
|
||||||
|
ok(!_.isEqual(new Date(2009, 11, 13), {
|
||||||
|
getTime: function(){
|
||||||
|
return 12606876e5;
|
||||||
|
}
|
||||||
|
}), "Date objects and objects with a <getTime> method are not equal");
|
||||||
|
ok(!_.isEqual(new Date("Curly"), new Date("Curly")), "Invalid dates are not equal");
|
||||||
|
|
||||||
|
// Functions.
|
||||||
|
ok(!_.isEqual(First, Second), "Different functions with identical bodies and source code representations are not equal");
|
||||||
|
|
||||||
|
// RegExps.
|
||||||
|
ok(_.isEqual(/(?:)/gim, /(?:)/gim), "RegExps with equivalent patterns and flags are equal");
|
||||||
|
ok(!_.isEqual(/(?:)/g, /(?:)/gi), "RegExps with equivalent patterns and different flags are not equal");
|
||||||
|
ok(!_.isEqual(/Moe/gim, /Curly/gim), "RegExps with different patterns and equivalent flags are not equal");
|
||||||
|
ok(!_.isEqual(/(?:)/gi, /(?:)/g), "Commutative equality is implemented for RegExps");
|
||||||
|
ok(!_.isEqual(/Curly/g, {source: "Larry", global: true, ignoreCase: false, multiline: false}), "RegExps and RegExp-like objects are not equal");
|
||||||
|
|
||||||
|
// Empty arrays, array-like objects, and object literals.
|
||||||
|
ok(_.isEqual({}, {}), "Empty object literals are equal");
|
||||||
|
ok(_.isEqual([], []), "Empty array literals are equal");
|
||||||
|
ok(_.isEqual([{}], [{}]), "Empty nested arrays and objects are equal");
|
||||||
|
ok(!_.isEqual({length: 0}, []), "Array-like objects and arrays are not equal.");
|
||||||
|
ok(!_.isEqual([], {length: 0}), "Commutative equality is implemented for array-like objects");
|
||||||
|
|
||||||
|
ok(!_.isEqual({}, []), "Object literals and array literals are not equal");
|
||||||
|
ok(!_.isEqual([], {}), "Commutative equality is implemented for objects and arrays");
|
||||||
|
|
||||||
|
// Arrays with primitive and object values.
|
||||||
|
ok(_.isEqual([1, "Larry", true], [1, "Larry", true]), "Arrays containing identical primitives are equal");
|
||||||
|
ok(_.isEqual([(/Moe/g), new Date(2009, 9, 25)], [(/Moe/g), new Date(2009, 9, 25)]), "Arrays containing equivalent elements are equal");
|
||||||
|
|
||||||
|
// Multi-dimensional arrays.
|
||||||
|
var a = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
|
||||||
|
var b = [new Number(47), false, "Larry", /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}];
|
||||||
|
ok(_.isEqual(a, b), "Arrays containing nested arrays and objects are recursively compared");
|
||||||
|
|
||||||
|
// Overwrite the methods defined in ES 5.1 section 15.4.4.
|
||||||
|
a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null;
|
||||||
|
b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null;
|
||||||
|
|
||||||
|
// Array elements and properties.
|
||||||
|
ok(_.isEqual(a, b), "Arrays containing equivalent elements and different non-numeric properties are equal");
|
||||||
|
a.push("White Rocks");
|
||||||
|
ok(!_.isEqual(a, b), "Arrays of different lengths are not equal");
|
||||||
|
a.push("East Boulder");
|
||||||
|
b.push("Gunbarrel Ranch", "Teller Farm");
|
||||||
|
ok(!_.isEqual(a, b), "Arrays of identical lengths containing different elements are not equal");
|
||||||
|
|
||||||
|
// Sparse arrays.
|
||||||
|
ok(_.isEqual(Array(3), Array(3)), "Sparse arrays of identical lengths are equal");
|
||||||
|
ok(!_.isEqual(Array(3), Array(6)), "Sparse arrays of different lengths are not equal when both are empty");
|
||||||
|
|
||||||
|
// Simple objects.
|
||||||
|
ok(_.isEqual({a: "Curly", b: 1, c: true}, {a: "Curly", b: 1, c: true}), "Objects containing identical primitives are equal");
|
||||||
|
ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), "Objects containing equivalent members are equal");
|
||||||
|
ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), "Objects of identical sizes with different values are not equal");
|
||||||
|
ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), "Objects of identical sizes with different property names are not equal");
|
||||||
|
ok(!_.isEqual({a: 1, b: 2}, {a: 1}), "Objects of different sizes are not equal");
|
||||||
|
ok(!_.isEqual({a: 1}, {a: 1, b: 2}), "Commutative equality is implemented for objects");
|
||||||
|
ok(!_.isEqual({x: 1, y: undefined}, {x: 1, z: 2}), "Objects with identical keys and different values are not equivalent");
|
||||||
|
|
||||||
|
// <A> contains nested objects and arrays.
|
||||||
|
a = {
|
||||||
|
name: new String("Moe Howard"),
|
||||||
|
age: new Number(77),
|
||||||
|
stooge: true,
|
||||||
|
hobbies: ["acting"],
|
||||||
|
film: {
|
||||||
|
name: "Sing a Song of Six Pants",
|
||||||
|
release: new Date(1947, 9, 30),
|
||||||
|
stars: [new String("Larry Fine"), "Shemp Howard"],
|
||||||
|
minutes: new Number(16),
|
||||||
|
seconds: 54
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// <B> contains equivalent nested objects and arrays.
|
||||||
|
b = {
|
||||||
|
name: new String("Moe Howard"),
|
||||||
|
age: new Number(77),
|
||||||
|
stooge: true,
|
||||||
|
hobbies: ["acting"],
|
||||||
|
film: {
|
||||||
|
name: "Sing a Song of Six Pants",
|
||||||
|
release: new Date(1947, 9, 30),
|
||||||
|
stars: [new String("Larry Fine"), "Shemp Howard"],
|
||||||
|
minutes: new Number(16),
|
||||||
|
seconds: 54
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ok(_.isEqual(a, b), "Objects with nested equivalent members are recursively compared");
|
||||||
|
|
||||||
|
// Instances.
|
||||||
|
ok(_.isEqual(new First, new First), "Object instances are equal");
|
||||||
|
ok(!_.isEqual(new First, new Second), "Objects with different constructors and identical own properties are not equal");
|
||||||
|
ok(!_.isEqual({value: 1}, new First), "Object instances and objects sharing equivalent properties are not equal");
|
||||||
|
ok(!_.isEqual({value: 2}, new Second), "The prototype chain of objects should not be examined");
|
||||||
|
|
||||||
|
// Circular Arrays.
|
||||||
|
(a = []).push(a);
|
||||||
|
(b = []).push(b);
|
||||||
|
ok(_.isEqual(a, b), "Arrays containing circular references are equal");
|
||||||
|
a.push(new String("Larry"));
|
||||||
|
b.push(new String("Larry"));
|
||||||
|
ok(_.isEqual(a, b), "Arrays containing circular references and equivalent properties are equal");
|
||||||
|
a.push("Shemp");
|
||||||
|
b.push("Curly");
|
||||||
|
ok(!_.isEqual(a, b), "Arrays containing circular references and different properties are not equal");
|
||||||
|
|
||||||
|
// More circular arrays #767.
|
||||||
|
a = ["everything is checked but", "this", "is not"];
|
||||||
|
a[1] = a;
|
||||||
|
b = ["everything is checked but", ["this", "array"], "is not"];
|
||||||
|
ok(!_.isEqual(a, b), "Comparison of circular references with non-circular references are not equal");
|
||||||
|
|
||||||
|
// Circular Objects.
|
||||||
|
a = {abc: null};
|
||||||
|
b = {abc: null};
|
||||||
|
a.abc = a;
|
||||||
|
b.abc = b;
|
||||||
|
ok(_.isEqual(a, b), "Objects containing circular references are equal");
|
||||||
|
a.def = 75;
|
||||||
|
b.def = 75;
|
||||||
|
ok(_.isEqual(a, b), "Objects containing circular references and equivalent properties are equal");
|
||||||
|
a.def = new Number(75);
|
||||||
|
b.def = new Number(63);
|
||||||
|
ok(!_.isEqual(a, b), "Objects containing circular references and different properties are not equal");
|
||||||
|
|
||||||
|
// More circular objects #767.
|
||||||
|
a = {everything: "is checked", but: "this", is: "not"};
|
||||||
|
a.but = a;
|
||||||
|
b = {everything: "is checked", but: {that:"object"}, is: "not"};
|
||||||
|
ok(!_.isEqual(a, b), "Comparison of circular references with non-circular object references are not equal");
|
||||||
|
|
||||||
|
// Cyclic Structures.
|
||||||
|
a = [{abc: null}];
|
||||||
|
b = [{abc: null}];
|
||||||
|
(a[0].abc = a).push(a);
|
||||||
|
(b[0].abc = b).push(b);
|
||||||
|
ok(_.isEqual(a, b), "Cyclic structures are equal");
|
||||||
|
a[0].def = "Larry";
|
||||||
|
b[0].def = "Larry";
|
||||||
|
ok(_.isEqual(a, b), "Cyclic structures containing equivalent properties are equal");
|
||||||
|
a[0].def = new String("Larry");
|
||||||
|
b[0].def = new String("Curly");
|
||||||
|
ok(!_.isEqual(a, b), "Cyclic structures containing different properties are not equal");
|
||||||
|
|
||||||
|
// Complex Circular References.
|
||||||
|
a = {foo: {b: {foo: {c: {foo: null}}}}};
|
||||||
|
b = {foo: {b: {foo: {c: {foo: null}}}}};
|
||||||
|
a.foo.b.foo.c.foo = a;
|
||||||
|
b.foo.b.foo.c.foo = b;
|
||||||
|
ok(_.isEqual(a, b), "Cyclic structures with nested and identically-named properties are equal");
|
||||||
|
|
||||||
|
// Chaining.
|
||||||
|
ok(!_.isEqual(_({x: 1, y: undefined}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal');
|
||||||
|
|
||||||
|
a = _({x: 1, y: 2}).chain();
|
||||||
|
b = _({x: 1, y: 2}).chain();
|
||||||
|
equal(_.isEqual(a.isEqual(b), _(true)), true, '<isEqual> can be chained');
|
||||||
|
|
||||||
|
//// Objects from another frame.
|
||||||
|
//ok(_.isEqual({}, iObject));
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isEmpty
|
||||||
|
func Test_underscore_objects_11(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isEmpty", function() {
|
||||||
|
ok(!_([1]).isEmpty(), '[1] is not empty');
|
||||||
|
ok(_.isEmpty([]), '[] is empty');
|
||||||
|
ok(!_.isEmpty({one : 1}), '{one : 1} is not empty');
|
||||||
|
ok(_.isEmpty({}), '{} is empty');
|
||||||
|
ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty');
|
||||||
|
ok(_.isEmpty(null), 'null is empty');
|
||||||
|
ok(_.isEmpty(), 'undefined is empty');
|
||||||
|
ok(_.isEmpty(''), 'the empty string is empty');
|
||||||
|
ok(!_.isEmpty('moe'), 'but other strings are not');
|
||||||
|
|
||||||
|
var obj = {one : 1};
|
||||||
|
delete obj.one;
|
||||||
|
ok(_.isEmpty(obj), 'deleting all the keys from an object empties it');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isArguments
|
||||||
|
func Test_underscore_objects_13(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isArguments", function() {
|
||||||
|
var args = (function(){ return arguments; })(1, 2, 3);
|
||||||
|
ok(!_.isArguments('string'), 'a string is not an arguments object');
|
||||||
|
ok(!_.isArguments(_.isArguments), 'a function is not an arguments object');
|
||||||
|
ok(_.isArguments(args), 'but the arguments object is an arguments object');
|
||||||
|
ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array');
|
||||||
|
ok(!_.isArguments([1,2,3]), 'and not vanilla arrays.');
|
||||||
|
//ok(_.isArguments(iArguments), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isObject
|
||||||
|
func Test_underscore_objects_14(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isObject", function() {
|
||||||
|
ok(_.isObject(arguments), 'the arguments object is object');
|
||||||
|
ok(_.isObject([1, 2, 3]), 'and arrays');
|
||||||
|
//ok(_.isObject($('html')[0]), 'and DOM element');
|
||||||
|
//ok(_.isObject(iElement), 'even from another frame');
|
||||||
|
ok(_.isObject(function () {}), 'and functions');
|
||||||
|
//ok(_.isObject(iFunction), 'even from another frame');
|
||||||
|
ok(!_.isObject(null), 'but not null');
|
||||||
|
ok(!_.isObject(undefined), 'and not undefined');
|
||||||
|
ok(!_.isObject('string'), 'and not string');
|
||||||
|
ok(!_.isObject(12), 'and not number');
|
||||||
|
ok(!_.isObject(true), 'and not boolean');
|
||||||
|
ok(_.isObject(new String('string')), 'but new String()');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isArray
|
||||||
|
func Test_underscore_objects_15(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isArray", function() {
|
||||||
|
ok(!_.isArray(arguments), 'the arguments object is not an array');
|
||||||
|
ok(_.isArray([1, 2, 3]), 'but arrays are');
|
||||||
|
//ok(_.isArray(iArray), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isString
|
||||||
|
func Test_underscore_objects_16(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isString", function() {
|
||||||
|
ok(!_.isString(document.body), 'the document body is not a string');
|
||||||
|
ok(_.isString([1, 2, 3].join(', ')), 'but strings are');
|
||||||
|
//ok(_.isString(iString), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isNumber
|
||||||
|
func Test_underscore_objects_17(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isNumber", function() {
|
||||||
|
ok(!_.isNumber('string'), 'a string is not a number');
|
||||||
|
ok(!_.isNumber(arguments), 'the arguments object is not a number');
|
||||||
|
ok(!_.isNumber(undefined), 'undefined is not a number');
|
||||||
|
ok(_.isNumber(3 * 4 - 7 / 10), 'but numbers are');
|
||||||
|
ok(_.isNumber(NaN), 'NaN *is* a number');
|
||||||
|
ok(_.isNumber(Infinity), 'Infinity is a number');
|
||||||
|
//ok(_.isNumber(iNumber), 'even from another frame');
|
||||||
|
ok(!_.isNumber('1'), 'numeric strings are not numbers');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isBoolean
|
||||||
|
func Test_underscore_objects_18(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isBoolean", function() {
|
||||||
|
ok(!_.isBoolean(2), 'a number is not a boolean');
|
||||||
|
ok(!_.isBoolean("string"), 'a string is not a boolean');
|
||||||
|
ok(!_.isBoolean("false"), 'the string "false" is not a boolean');
|
||||||
|
ok(!_.isBoolean("true"), 'the string "true" is not a boolean');
|
||||||
|
ok(!_.isBoolean(arguments), 'the arguments object is not a boolean');
|
||||||
|
ok(!_.isBoolean(undefined), 'undefined is not a boolean');
|
||||||
|
ok(!_.isBoolean(NaN), 'NaN is not a boolean');
|
||||||
|
ok(!_.isBoolean(null), 'null is not a boolean');
|
||||||
|
ok(_.isBoolean(true), 'but true is');
|
||||||
|
ok(_.isBoolean(false), 'and so is false');
|
||||||
|
//ok(_.isBoolean(iBoolean), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isFunction
|
||||||
|
func Test_underscore_objects_19(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isFunction", function() {
|
||||||
|
ok(!_.isFunction([1, 2, 3]), 'arrays are not functions');
|
||||||
|
ok(!_.isFunction('moe'), 'strings are not functions');
|
||||||
|
ok(_.isFunction(_.isFunction), 'but functions are');
|
||||||
|
//ok(_.isFunction(iFunction), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isDate
|
||||||
|
func Test_underscore_objects_20(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isDate", function() {
|
||||||
|
ok(!_.isDate(100), 'numbers are not dates');
|
||||||
|
ok(!_.isDate({}), 'objects are not dates');
|
||||||
|
ok(_.isDate(new Date()), 'but dates are');
|
||||||
|
//ok(_.isDate(iDate), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isRegExp
|
||||||
|
func Test_underscore_objects_21(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isRegExp", function() {
|
||||||
|
ok(!_.isRegExp(_.identity), 'functions are not RegExps');
|
||||||
|
ok(_.isRegExp(/identity/), 'but RegExps are');
|
||||||
|
//ok(_.isRegExp(iRegExp), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isFinite
|
||||||
|
func Test_underscore_objects_22(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isFinite", function() {
|
||||||
|
ok(!_.isFinite(undefined), 'undefined is not Finite');
|
||||||
|
ok(!_.isFinite(null), 'null is not Finite');
|
||||||
|
ok(!_.isFinite(NaN), 'NaN is not Finite');
|
||||||
|
ok(!_.isFinite(Infinity), 'Infinity is not Finite');
|
||||||
|
ok(!_.isFinite(-Infinity), '-Infinity is not Finite');
|
||||||
|
ok(_.isFinite('12'), 'Numeric strings are numbers');
|
||||||
|
ok(!_.isFinite('1a'), 'Non numeric strings are not numbers');
|
||||||
|
ok(!_.isFinite(''), 'Empty strings are not numbers');
|
||||||
|
// FIXME
|
||||||
|
//var obj = new Number(5);
|
||||||
|
//ok(_.isFinite(obj), 'Number instances can be finite');
|
||||||
|
ok(_.isFinite(0), '0 is Finite');
|
||||||
|
ok(_.isFinite(123), 'Ints are Finite');
|
||||||
|
ok(_.isFinite(-12.44), 'Floats are Finite');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isNaN
|
||||||
|
func Test_underscore_objects_23(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isNaN", function() {
|
||||||
|
ok(!_.isNaN(undefined), 'undefined is not NaN');
|
||||||
|
ok(!_.isNaN(null), 'null is not NaN');
|
||||||
|
ok(!_.isNaN(0), '0 is not NaN');
|
||||||
|
ok(_.isNaN(NaN), 'but NaN is');
|
||||||
|
//ok(_.isNaN(iNaN), 'even from another frame');
|
||||||
|
ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isNull
|
||||||
|
func Test_underscore_objects_24(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isNull", function() {
|
||||||
|
ok(!_.isNull(undefined), 'undefined is not null');
|
||||||
|
ok(!_.isNull(NaN), 'NaN is not null');
|
||||||
|
ok(_.isNull(null), 'but null is');
|
||||||
|
//ok(_.isNull(iNull), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isUndefined
|
||||||
|
func Test_underscore_objects_25(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("isUndefined", function() {
|
||||||
|
ok(!_.isUndefined(1), 'numbers are defined');
|
||||||
|
ok(!_.isUndefined(null), 'null is defined');
|
||||||
|
ok(!_.isUndefined(false), 'false is defined');
|
||||||
|
ok(!_.isUndefined(NaN), 'NaN is defined');
|
||||||
|
ok(_.isUndefined(), 'nothing is undefined');
|
||||||
|
ok(_.isUndefined(undefined), 'undefined is undefined');
|
||||||
|
//ok(_.isUndefined(iUndefined), 'even from another frame');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// tap
|
||||||
|
func Test_underscore_objects_26(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("tap", function() {
|
||||||
|
var intercepted = null;
|
||||||
|
var interceptor = function(obj) { intercepted = obj; };
|
||||||
|
var returned = _.tap(1, interceptor);
|
||||||
|
equal(intercepted, 1, "passes tapped object to interceptor");
|
||||||
|
equal(returned, 1, "returns tapped object");
|
||||||
|
|
||||||
|
returned = _([1,2,3]).chain().
|
||||||
|
map(function(n){ return n * 2; }).
|
||||||
|
max().
|
||||||
|
tap(interceptor).
|
||||||
|
value();
|
||||||
|
ok(returned == 6 && intercepted == 6, 'can use tapped objects in a chain');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// has
|
||||||
|
func Test_underscore_objects_27(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("has", function () {
|
||||||
|
var obj = {foo: "bar", func: function () {} };
|
||||||
|
ok (_.has(obj, "foo"), "has() checks that the object has a property.");
|
||||||
|
ok (_.has(obj, "baz") == false, "has() returns false if the object doesn't have the property.");
|
||||||
|
ok (_.has(obj, "func"), "has() works for functions too.");
|
||||||
|
obj.hasOwnProperty = null;
|
||||||
|
ok (_.has(obj, "foo"), "has() works even when the hasOwnProperty method is deleted.");
|
||||||
|
var child = {};
|
||||||
|
child.prototype = obj;
|
||||||
|
ok (_.has(child, "foo") == false, "has() does not check the prototype chain for a property.")
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
1867
underscore_test.go
1867
underscore_test.go
File diff suppressed because it is too large
Load Diff
422
underscore_utility_test.go
Normal file
422
underscore_utility_test.go
Normal file
|
@ -0,0 +1,422 @@
|
||||||
|
package otto
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/robertkrimen/terst"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// #750 - Return _ instance.
|
||||||
|
func Test_underscore_utility_0(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("#750 - Return _ instance.", 2, function() {
|
||||||
|
var instance = _([]);
|
||||||
|
ok(_(instance) === instance);
|
||||||
|
ok(new _(instance) === instance);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// identity
|
||||||
|
func Test_underscore_utility_1(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("identity", function() {
|
||||||
|
var moe = {name : 'moe'};
|
||||||
|
equal(_.identity(moe), moe, 'moe is the same as his identity');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// random
|
||||||
|
func Test_underscore_utility_2(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("random", function() {
|
||||||
|
var array = _.range(1000);
|
||||||
|
var min = Math.pow(2, 31);
|
||||||
|
var max = Math.pow(2, 62);
|
||||||
|
|
||||||
|
ok(_.every(array, function() {
|
||||||
|
return _.random(min, max) >= min;
|
||||||
|
}), "should produce a random number greater than or equal to the minimum number");
|
||||||
|
|
||||||
|
ok(_.some(array, function() {
|
||||||
|
return _.random(Number.MAX_VALUE) > 0;
|
||||||
|
}), "should produce a random number when passed <Number.MAX_VALUE>");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// uniqueId
|
||||||
|
func Test_underscore_utility_3(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("uniqueId", function() {
|
||||||
|
var ids = [], i = 0;
|
||||||
|
while(i++ < 100) ids.push(_.uniqueId());
|
||||||
|
equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// times
|
||||||
|
func Test_underscore_utility_4(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("times", function() {
|
||||||
|
var vals = [];
|
||||||
|
_.times(3, function (i) { vals.push(i); });
|
||||||
|
ok(_.isEqual(vals, [0,1,2]), "is 0 indexed");
|
||||||
|
//
|
||||||
|
vals = [];
|
||||||
|
_(3).times(function(i) { vals.push(i); });
|
||||||
|
ok(_.isEqual(vals, [0,1,2]), "works as a wrapper");
|
||||||
|
// collects return values
|
||||||
|
ok(_.isEqual([0, 1, 2], _.times(3, function(i) { return i; })), "collects return values");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// mixin
|
||||||
|
func Test_underscore_utility_5(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("mixin", function() {
|
||||||
|
_.mixin({
|
||||||
|
myReverse: function(string) {
|
||||||
|
return string.split('').reverse().join('');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
equal(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _');
|
||||||
|
equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// _.escape
|
||||||
|
func Test_underscore_utility_6(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("_.escape", function() {
|
||||||
|
equal(_.escape("Curly & Moe"), "Curly & Moe");
|
||||||
|
equal(_.escape("Curly & Moe"), "Curly &amp; Moe");
|
||||||
|
equal(_.escape(null), '');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// _.unescape
|
||||||
|
func Test_underscore_utility_7(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("_.unescape", function() {
|
||||||
|
var string = "Curly & Moe";
|
||||||
|
equal(_.unescape("Curly & Moe"), string);
|
||||||
|
equal(_.unescape("Curly &amp; Moe"), "Curly & Moe");
|
||||||
|
equal(_.unescape(null), '');
|
||||||
|
equal(_.unescape(_.escape(string)), string);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// template
|
||||||
|
func Test_underscore_utility_8(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test("template", function() {
|
||||||
|
var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
|
||||||
|
var result = basicTemplate({thing : 'This'});
|
||||||
|
equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
|
||||||
|
|
||||||
|
var sansSemicolonTemplate = _.template("A <% this %> B");
|
||||||
|
equal(sansSemicolonTemplate(), "A B");
|
||||||
|
|
||||||
|
var backslashTemplate = _.template("<%= thing %> is \\ridanculous");
|
||||||
|
equal(backslashTemplate({thing: 'This'}), "This is \\ridanculous");
|
||||||
|
|
||||||
|
var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>');
|
||||||
|
equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.');
|
||||||
|
|
||||||
|
var fancyTemplate = _.template("<ul><% \
|
||||||
|
for (var key in people) { \
|
||||||
|
%><li><%= people[key] %></li><% } %></ul>");
|
||||||
|
result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
|
||||||
|
|
||||||
|
var escapedCharsInJavascriptTemplate = _.template("<ul><% _.each(numbers.split('\\n'), function(item) { %><li><%= item %></li><% }) %></ul>");
|
||||||
|
result = escapedCharsInJavascriptTemplate({numbers: "one\ntwo\nthree\nfour"});
|
||||||
|
equal(result, "<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>", 'Can use escaped characters (e.g. \\n) in Javascript');
|
||||||
|
|
||||||
|
var namespaceCollisionTemplate = _.template("<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %><div class=\"thumbnail\" rel=\"<%= p %>\"></div><% }); %>");
|
||||||
|
result = namespaceCollisionTemplate({
|
||||||
|
pageCount: 3,
|
||||||
|
thumbnails: {
|
||||||
|
1: "p1-thumbnail.gif",
|
||||||
|
2: "p2-thumbnail.gif",
|
||||||
|
3: "p3-thumbnail.gif"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//equal(result, "3 p3-thumbnail.gif <div class=\"thumbnail\" rel=\"p1-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p2-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p3-thumbnail.gif\"></div>");
|
||||||
|
|
||||||
|
var noInterpolateTemplate = _.template("<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
|
||||||
|
result = noInterpolateTemplate();
|
||||||
|
equal(result, "<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
|
||||||
|
|
||||||
|
var quoteTemplate = _.template("It's its, not it's");
|
||||||
|
equal(quoteTemplate({}), "It's its, not it's");
|
||||||
|
|
||||||
|
var quoteInStatementAndBody = _.template("<%\
|
||||||
|
if(foo == 'bar'){ \
|
||||||
|
%>Statement quotes and 'quotes'.<% } %>");
|
||||||
|
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
|
||||||
|
|
||||||
|
var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.');
|
||||||
|
equal(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.');
|
||||||
|
|
||||||
|
var template = _.template("<i><%- value %></i>");
|
||||||
|
var result = template({value: "<script>"});
|
||||||
|
equal(result, '<i><script></i>');
|
||||||
|
|
||||||
|
var stooge = {
|
||||||
|
name: "Moe",
|
||||||
|
template: _.template("I'm <%= this.name %>")
|
||||||
|
};
|
||||||
|
equal(stooge.template(), "I'm Moe");
|
||||||
|
|
||||||
|
//if (!$.browser.msie) {
|
||||||
|
// var fromHTML = _.template($('#template').html());
|
||||||
|
// equal(fromHTML({data : 12345}).replace(/\s/g, ''), '<li>24690</li>');
|
||||||
|
//}
|
||||||
|
|
||||||
|
_.templateSettings = {
|
||||||
|
evaluate : /\{\{([\s\S]+?)\}\}/g,
|
||||||
|
interpolate : /\{\{=([\s\S]+?)\}\}/g
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//var custom = _.template("<ul>{{ for (var key in people) { }}<li>{{= people[key] }}</li>{{ } }}</ul>");
|
||||||
|
//result = custom({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
|
||||||
|
//equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
|
||||||
|
|
||||||
|
var customQuote = _.template("It's its, not it's");
|
||||||
|
equal(customQuote({}), "It's its, not it's");
|
||||||
|
|
||||||
|
var quoteInStatementAndBody = _.template("{{ if(foo == 'bar'){ }}Statement quotes and 'quotes'.{{ } }}");
|
||||||
|
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
|
||||||
|
|
||||||
|
_.templateSettings = {
|
||||||
|
evaluate : /<\?([\s\S]+?)\?>/g,
|
||||||
|
interpolate : /<\?=([\s\S]+?)\?>/g
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: Property ordering unreliable
|
||||||
|
//var customWithSpecialChars = _.template("<ul><? for (var key in people) { ?><li><?= people[key] ?></li><? } ?></ul>");
|
||||||
|
//result = customWithSpecialChars({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
|
||||||
|
//equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
|
||||||
|
|
||||||
|
var customWithSpecialCharsQuote = _.template("It's its, not it's");
|
||||||
|
equal(customWithSpecialCharsQuote({}), "It's its, not it's");
|
||||||
|
|
||||||
|
var quoteInStatementAndBody = _.template("<? if(foo == 'bar'){ ?>Statement quotes and 'quotes'.<? } ?>");
|
||||||
|
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
|
||||||
|
|
||||||
|
_.templateSettings = {
|
||||||
|
interpolate : /\{\{(.+?)\}\}/g
|
||||||
|
};
|
||||||
|
|
||||||
|
var mustache = _.template("Hello {{planet}}!");
|
||||||
|
equal(mustache({planet : "World"}), "Hello World!", "can mimic mustache.js");
|
||||||
|
|
||||||
|
var templateWithNull = _.template("a null undefined {{planet}}");
|
||||||
|
equal(templateWithNull({planet : "world"}), "a null undefined world", "can handle missing escape and evaluate settings");
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// _.template provides the generated function source, when a SyntaxError occurs
|
||||||
|
func Test_underscore_utility_9(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('_.template provides the generated function source, when a SyntaxError occurs', function() {
|
||||||
|
try {
|
||||||
|
_.template('<b><%= if x %></b>');
|
||||||
|
} catch (ex) {
|
||||||
|
var source = ex.source;
|
||||||
|
}
|
||||||
|
ok(/__p/.test(source));
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// _.template handles \\u2028 & \\u2029
|
||||||
|
func Test_underscore_utility_10(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('_.template handles \\u2028 & \\u2029', function() {
|
||||||
|
var tmpl = _.template('<p>\u2028<%= "\\u2028\\u2029" %>\u2029</p>');
|
||||||
|
strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// result calls functions and returns primitives
|
||||||
|
func Test_underscore_utility_11(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('result calls functions and returns primitives', function() {
|
||||||
|
var obj = {w: '', x: 'x', y: function(){ return this.x; }};
|
||||||
|
strictEqual(_.result(obj, 'w'), '');
|
||||||
|
strictEqual(_.result(obj, 'x'), 'x');
|
||||||
|
strictEqual(_.result(obj, 'y'), 'x');
|
||||||
|
strictEqual(_.result(obj, 'z'), undefined);
|
||||||
|
// FIXME
|
||||||
|
//strictEqual(_.result(null, 'x'), undefined);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// _.templateSettings.variable
|
||||||
|
func Test_underscore_utility_12(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('_.templateSettings.variable', function() {
|
||||||
|
var s = '<%=data.x%>';
|
||||||
|
var data = {x: 'x'};
|
||||||
|
strictEqual(_.template(s, data, {variable: 'data'}), 'x');
|
||||||
|
_.templateSettings.variable = 'data';
|
||||||
|
strictEqual(_.template(s)(data), 'x');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #547 - _.templateSettings is unchanged by custom settings.
|
||||||
|
func Test_underscore_utility_13(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('#547 - _.templateSettings is unchanged by custom settings.', function() {
|
||||||
|
ok(!_.templateSettings.variable);
|
||||||
|
_.template('', {}, {variable: 'x'});
|
||||||
|
ok(!_.templateSettings.variable);
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #556 - undefined template variables.
|
||||||
|
func Test_underscore_utility_14(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('#556 - undefined template variables.', function() {
|
||||||
|
var template = _.template('<%=x%>');
|
||||||
|
strictEqual(template({x: null}), '');
|
||||||
|
strictEqual(template({x: undefined}), '');
|
||||||
|
|
||||||
|
var templateEscaped = _.template('<%-x%>');
|
||||||
|
strictEqual(templateEscaped({x: null}), '');
|
||||||
|
strictEqual(templateEscaped({x: undefined}), '');
|
||||||
|
|
||||||
|
var templateWithProperty = _.template('<%=x.foo%>');
|
||||||
|
strictEqual(templateWithProperty({x: {} }), '');
|
||||||
|
strictEqual(templateWithProperty({x: {} }), '');
|
||||||
|
|
||||||
|
var templateWithPropertyEscaped = _.template('<%-x.foo%>');
|
||||||
|
strictEqual(templateWithPropertyEscaped({x: {} }), '');
|
||||||
|
strictEqual(templateWithPropertyEscaped({x: {} }), '');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// interpolate evaluates code only once.
|
||||||
|
func Test_underscore_utility_15(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('interpolate evaluates code only once.', 2, function() {
|
||||||
|
var count = 0;
|
||||||
|
var template = _.template('<%= f() %>');
|
||||||
|
template({f: function(){ ok(!(count++)); }});
|
||||||
|
|
||||||
|
var countEscaped = 0;
|
||||||
|
var templateEscaped = _.template('<%- f() %>');
|
||||||
|
templateEscaped({f: function(){ ok(!(countEscaped++)); }});
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #746 - _.template settings are not modified.
|
||||||
|
func Test_underscore_utility_16(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('#746 - _.template settings are not modified.', 1, function() {
|
||||||
|
var settings = {};
|
||||||
|
_.template('', null, settings);
|
||||||
|
deepEqual(settings, {});
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #779 - delimeters are applied to unescaped text.
|
||||||
|
func Test_underscore_utility_17(t *testing.T) {
|
||||||
|
Terst(t)
|
||||||
|
|
||||||
|
test := underscoreTest()
|
||||||
|
|
||||||
|
test(`
|
||||||
|
test('#779 - delimeters are applied to unescaped text.', 1, function() {
|
||||||
|
var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
|
||||||
|
strictEqual(template(), '<<\nx\n>>');
|
||||||
|
});
|
||||||
|
`)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user