Socket
Socket
Sign inDemoInstall

mol-proto

Package Overview
Dependencies
0
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.5 to 0.1.0

lib/proto_array.js

309

lib/proto.js
'use strict';
var _;
var proto = _ = {
extendProto: extendProto,
createSubclass: createSubclass,
makeSubclass: makeSubclass,
extend: extend,
clone: clone,
deepExtend: deepExtend,
allKeys: Object.getOwnPropertyNames.bind(Object),
keyOf: keyOf,
allKeysOf: allKeysOf,
eachKey: eachKey,
mapKeys: mapKeys,
appendArray: appendArray,
prependArray: prependArray,
toArray: toArray,
firstUpperCase: firstUpperCase,
firstLowerCase: firstLowerCase
};
var utils = require('./utils');
if (typeof window == 'object') {
// preserve existing _ object
if (window._)
proto.underscore = window._
/**
* [__Prototype functions__](prototype.js.html)
*
* - [extendProto](prototype.js.html#extendProto)
* - [createSubclass](prototype.js.html#createSubclass)
* - [makeSubclass](prototype.js.html#makeSubclass)
*/
var prototypeMethods = require('./proto_prototype');
// expose global _
window._ = proto;
}
if (typeof module == 'object' && module.exports)
// export for node/browserify
module.exports = proto;
/**
* [__Object functions__](object.js.html)
*
* - [extend](object.js.html#extend)
* - [clone](object.js.html#clone)
* - [defineProperty](object.js.html#defineProperty)
* - [defineProperties](object.js.html#defineProperties)
* - [deepExtend](object.js.html#deepExtend)
* - [allKeys](object.js.html#allKeys)
* - [keyOf](object.js.html#keyOf)
* - [allKeysOf](object.js.html#allKeysOf)
* - [eachKey](object.js.html#eachKey)
* - [mapKeys](object.js.html#mapKeys)
*/
var objectMethods = require('./proto_object');
function extendProto(self, methods) {
var propDescriptors = {};
_.eachKey(methods, function(method, name) {
propDescriptors[name] = {
enumerable: false,
configurable: false,
writable: false,
value: method
};
});
/**
* [__Array functions__](array.js.html)
*
* - [appendArray](array.js.html#appendArray)
* - [prependArray](array.js.html#prependArray)
* - [toArray](array.js.html#toArray)
* - [object](array.js.html#object)
* - [mapToObject](array.js.html#mapToObject)
*
* Functions that Array [implements natively](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods) are also added - they can be used with array-like objects and for chaining (native functions are always called).
*/
var arrayMethods = require('./proto_array');
Object.defineProperties(self.prototype, propDescriptors);
return self;
}
/**
* [__Function functions__](function.js.html)
*
* - [partial](function.js.html#partial)
* - [memoize](function.js.html#memoize)
*/
var functionMethods = require('./proto_function');
function extend(self, obj, onlyEnumerable) {
var propDescriptors = {};
_.eachKey(obj, function(value, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
propDescriptors[prop] = descriptor;
}, this, onlyEnumerable);
/**
* [__String functions__](string.js.html)
*
* - [firstUpperCase](string.js.html#firstUpperCase)
* - [firstLowerCase](string.js.html#firstLowerCase)
*/
var stringMethods = require('./proto_string');
Object.defineProperties(self, propDescriptors);
return self;
}
/**
* Chaining
* ========
*
* `_` can be used to create a wrapped value (object, function, array, etc.) to allow chaining of Proto functions.
* To unwrap, `_` method of a wrapped value should be used.
* Usage:
* ```
* var arr = _({ 0: 3, 1: 4, 2: 5, length: 3})
* .toArray()
* .prependArray([1, 2])
* .appendArray([6, 7, 8])
* ._();
* ```
* A wrapped object is an instance of `_` (`Proto` class).
*
* Chaining is implemented for development convenience, but it has performance overhead, not only to wrap and unwrap values but in each function call.
* Although all Proto functions are implemented as methods operating on this and the overhead to redefine them as functions is very small, the overhead to redefine them as methods of wrapped value is slightly higher - chaining is 15-25% slower than using functions (properties of _ that take the first parameter).
* In cases when performance is critical, you may want to avoid using chaining.
*
* @param {Any} self A value to be wrapped
* @return {Proto}
*/
function Proto(self) {
// wrap passed parameter in _ object
var wrapped = Object.create(Proto.prototype);
wrapped.self = self;
return wrapped;
};
var _ = Proto;
function deepExtend(self, obj, onlyEnumerable) {
return _extendTree(self, obj, onlyEnumerable, []);
}
// store raw methods from different modules in __ object (double "_")
var __ = objectMethods.clone.call(objectMethods);
__.extend.call(__, prototypeMethods);
__.extend.call(__, arrayMethods);
__.extend.call(__, stringMethods);
__.extend.call(__, functionMethods);
function _extendTree(selfNode, objNode, onlyEnumerable, objTraversed) {
if (objTraversed.indexOf(objNode) >= 0) return; // node already traversed
objTraversed.push(objNode);
// add __ as property of Proto, so they can be used as mixins in other classes
__.defineProperty(Proto, '__', __);
_.eachKey(objNode, function(value, prop) {
var descriptor = Object.getOwnPropertyDescriptor(objNode, prop);
if (typeof value == 'object') {
if (selfNode.hasOwnProperty(prop) && typeof selfNode[prop] == 'object')
_extendTree(selfNode[prop], value, onlyEnumerable, objTraversed)
else
Object.defineProperty(selfNode, prop, descriptor);
} else
Object.defineProperty(selfNode, prop, descriptor);
}, this, onlyEnumerable);
return selfNode;
}
// add _ method to unwrap wrapped value (Proto instance)
function unwrapProto() { return this.self; }
__.extendProto.call(Proto, { _: unwrapProto });
function clone(obj) {
var clonedObject = Object.create(obj.constructor.prototype);
_.extend(clonedObject, obj);
return clonedObject;
}
// add functions that take first parameter instead of "this" and wrapped value instance methods to Proto
[ prototypeMethods, objectMethods, arrayMethods, functionMethods, stringMethods ]
.forEach(addFuncsAndMethodsToProto);
function addFuncsAndMethodsToProto(methodsMap) {
// make Proto functions
var protoFuncs = __.mapKeys.call(methodsMap, utils.makeProtoFunction);
__.extend.call(Proto, protoFuncs);
function createSubclass(thisClass, name, applyConstructor) {
var subclass;
// name is optional
name = name || '';
// apply superclass constructor
var constructorCode = applyConstructor === false
? ''
: 'thisClass.apply(this, arguments);';
eval('subclass = function ' + name + '(){ ' + constructorCode + ' }');
_.makeSubclass(subclass, thisClass);
// copy class methods
// - for them to work correctly they should not explictly use superclass name
// and use "this" instead
_.extend(subclass, thisClass, true);
return subclass;
// make Proto wrapped value methods
var protoInstanceMethods = __.mapKeys.call(methodsMap,
utils.makeProtoInstanceMethod);
__.extendProto.call(Proto, protoInstanceMethods);
}
function makeSubclass(thisClass, Superclass) {
// prototype chain
thisClass.prototype = Object.create(Superclass.prototype);
// subclass identity
_.extendProto(thisClass, {
constructor: thisClass
});
return thisClass;
}
/**
* In windows environment, a global `_` value is preserved in `_.underscore`
*/
if (typeof window == 'object') {
// preserve existing _ object
if (window._)
Proto.underscore = window._
function keyOf(self, searchElement, onlyEnumerable) {
var properties = onlyEnumerable
? Object.keys(self)
: _.allKeys(self);
for (var i = 0; i < properties.length; i++)
if (searchElement === self[properties[i]])
return properties[i];
return undefined;
// expose global _
window._ = Proto;
}
function allKeysOf(self, searchElement, onlyEnumerable) {
var properties = onlyEnumerable
? Object.keys(self)
: _.allKeys(self);
var keys = properties.filter(function(prop) {
return searchElement === self[prop];
});
return keys;
}
function eachKey(self, callback, thisArg, onlyEnumerable) {
var properties = onlyEnumerable
? Object.keys(self)
: _.allKeys(self);
properties.forEach(function(prop) {
callback.call(thisArg, self[prop], prop, self);
});
}
function mapKeys(self, callback, thisArg, onlyEnumerable) {
var mapResult = {};
_.eachKey(self, mapProperty, thisArg, onlyEnumerable);
return mapResult;
function mapProperty(value, key) {
var descriptor = Object.getOwnPropertyDescriptor(self, key);
if (descriptor.enumerable || ! onlyEnumerable) {
descriptor.value = callback.call(this, value, key, self);
Object.defineProperty(mapResult, key, descriptor);
}
}
}
function appendArray(self, arrayToAppend) {
if (! arrayToAppend.length) return self;
var args = [self.length, 0].concat(arrayToAppend);
Array.prototype.splice.apply(self, args);
return self;
}
function prependArray(self, arrayToPrepend) {
if (! arrayToPrepend.length) return self;
var args = [0, 0].concat(arrayToPrepend);
Array.prototype.splice.apply(self, args);
return self;
}
function toArray(arrayLike) {
var arr = [];
Array.prototype.forEach.call(arrayLike, function(item) {
arr.push(item)
});
return arr;
}
function firstUpperCase(str) {
return str[0].toUpperCase() + str.slice(1);
}
function firstLowerCase(str) {
return str[0].toLowerCase() + str.slice(1);
}
if (typeof module == 'object' && module.exports)
// export for node/browserify
module.exports = Proto;
{
"name": "mol-proto",
"version": "0.0.5",
"description": "Prototypes aware object manipulation library for node and modern browsers",
"version": "0.1.0",
"description": "ES5 object manipulation library for node and modern browsers",
"main": "lib/proto.js",

@@ -20,4 +20,4 @@ "scripts": {

"async": "~0.2.9",
"mocha": "~1.14.0"
"mocha": "~1.15.1"
}
}
proto
=====
Prototypes aware object manipulation library for node and modern browsers
ES5-compatible object manipulation library for node and modern browsers
[![Build Status](https://travis-ci.org/MailOnline/proto.png?branch=master)](https://travis-ci.org/MailOnline/proto)
Check documentation at http://mailonline.github.io/proto/
Why not use underscore or lo-dash

@@ -18,2 +21,3 @@ ---------------------------------

between arrays and objects (maps), e.g. when _each_ function is used.
7. Underscore has clumbersome chaining syntax, chaining in proto is more succinct.

@@ -48,238 +52,32 @@

* [__Prototype functions__](#prototype-functions)
* [extendProto](#extendproto-constructor-properties)
* [createSubclass](#createsubclass-constructor--name--applyconstructor)
* [makeSubclass](#makesubclass-thisclass-superclass)
* [__Prototype functions__](http://mailonline.github.io/proto/prototype.js.html)
* [extendProto](http://mailonline.github.io/proto/prototype.js.html#extendProto)
* [createSubclass](http://mailonline.github.io/proto/prototype.js.html#createSubclass)
* [makeSubclass](http://mailonline.github.io/proto/prototype.js.html#makeSubclass)
* [__Object functions__](#object-functions)
* [extend](#extend-self-obj--onlyenumerable)
* [clone](#clone-self)
* [deepExtend](#deepextend-self-obj--onlyenumerable)
* [allKeys](#allkeys-self)
* [keyOf](#keyof-self-searchelement--onlyenumerable)
* [allKeysOf](#allkeysof-self-searchelement--onlyenumerable)
* [eachKey](#eachkey-self-callback--thisarg--onlyenumerable)
* [mapKeys](#mapkeys-self-callback--thisarg--onlyenumerable)
* [__Object functions__](http://mailonline.github.io/proto/object.js.html)
* [extend](http://mailonline.github.io/proto/object.js.html#extend)
* [clone](http://mailonline.github.io/proto/object.js.html#clone)
* [defineProperty](http://mailonline.github.io/proto/object.js.html#defineProperty)
* [defineProperties](http://mailonline.github.io/proto/object.js.html#defineProperties)
* [deepExtend](http://mailonline.github.io/proto/object.js.html#deepExtend)
* [allKeys](http://mailonline.github.io/proto/object.js.html#allKeys)
* [keyOf](http://mailonline.github.io/proto/object.js.html#keyOf)
* [allKeysOf](http://mailonline.github.io/proto/object.js.html#allKeysOf)
* [eachKey](http://mailonline.github.io/proto/object.js.html#eachKey)
* [mapKeys](http://mailonline.github.io/proto/object.js.html#mapKeys)
* [__Array functions__](#array-functions)
* [appendArray](#appendarray-self-arraytoappend)
* [prependArray](#prependarray-self-arraytoprepend)
* [toArray](#toarray-arraylike)
* [__Array functions__](http://mailonline.github.io/proto/array.js.html)
* [appendArray](http://mailonline.github.io/proto/array.js.html#appendArray)
* [prependArray](http://mailonline.github.io/proto/array.js.html#prependArray)
* [toArray](http://mailonline.github.io/proto/array.js.html#toArray)
* [object](http://mailonline.github.io/proto/array.js.html#object)
* [mapToObject](http://mailonline.github.io/proto/array.js.html#mapToObject)
* [__String functions__](#string-functions)
* [firstUpperCase](#firstuppercase-str)
* [firstLowerCase](#firstlowercase-str)
* [__Function functions__](http://mailonline.github.io/proto/function.js.html)
* [partial](http://mailonline.github.io/proto/function.js.html#partial)
* [memoize](http://mailonline.github.io/proto/function.js.html#memoize)
Prototype functions
-------------------
#### __extendProto__ (_Constructor_, _properties_)
Adds non-enumerable, non-configurable and non-writable properties to the prototype of constructor function
```javascript
function MyClass() {}
_.extendProto(MyClass, {
method1: function() {},
method2: function() {}
});
```
To extend class via object:
```javascript
_.extendProto(obj.constructor, { /* ... */ } );
```
#### __createSubclass__ (_Constructor_ [, _name_ [, _applyConstructor_]])
Makes a subclass of class _Constructor_.
The returned function will have specified _name_ if supplied.
The constructor of superclass will be called in subclass constructor by default
unless _applyConstructor_ === false (not just falsy).
#### __makeSubclass__ (_thisClass_, _Superclass_)
Sets up prototype chain to change _thisClass_ (a constructor function)
so that it becomes a subclass of _Superclass_.
Object functions
----------------
#### __extend__ (_self_, _obj_ [, _onlyEnumerable_])
Extends object _self_ with an object _obj_ copying all own properties
(not those inherited via prototype chain), including non-enumerable properties
(unless _onlyEnumerable_ is truthy)
#### __clone__ (_self_)
Makes a shallow clone of object _self_ creating an instance of the same class.
Although it can be used to clone an Array and the returned object will look and
behave like a real array (it will be an instance of Array),
depending on JavaScript implementation it may store items inefficiently (not
sequentially) and it may affect performance.
If you need to clone array, use
```javascript
var clonedArray = [].concat(arr);
```
#### __deepExtend__ (_self_, _obj_ [, _onlyEnumerable_)
Extends object on all levels without overwriting existing properties that are
objects:
```javascript
var obj = {
inner: {
a: 1
}
};
_.deepExtend(obj, {
inner: {
b: 2
}
});
assert.deepEqual(obj, {
inner: {
a: 1,
b: 2
}
}); // assert passes
```
#### __allKeys__ (_self_)
Returns array of property names of an object _self_.
This function is defined in this way:
```javascript
_.allKeys = Object.getOwnPropertyNames.bind(Object)
```
#### __keyOf__ (_self_, _searchElement_ [, _onlyEnumerable_])
An analogue of _indexOf_ method of Array prototype.
Returns the _key_ of _searchElement_ in the object _self_.
As object keys are unsorted, if there are several keys that hold _searchElement_
any of them can be returned. Use _allKeysOf_ to return all keys.
All own properties are searched (not those inherited via prototype chain),
including non-enumerable properties (unless _onlyEnumerable_ is truthy).
#### __allKeysOf__ (_self_, _searchElement_ [, _onlyEnumerable_])
Works similarly to the previous function, but returns the array of keys
holding _searchElement_ as their value.
#### __eachKey__ (_self_, _callback_ [, _thisArg_ [, _onlyEnumerable_]])
An analogue of [_forEach_ method][Array forEach] of Array prototype.
Iterates all own properties of _self_ (or only enumerable own properties
if _onlyEnumerable_ is truthy) calling callback for each key.
Callback is passed _value_, _key_ and _self_, its return value is not used.
If _thisArg_ is set it will be the context (the value of _this_) in _callback_.
This method should not be used with arrays, it will include _length_ property
in iteration.
To iterate array-like objects (e.g., _arguments_ pseudo-array) use:
```javascript
Array.prototype.forEach.call(arguments, callback, thisArg);
```
#### __mapKeys__ (_self_, _callback_ [, _thisArg_ [, _onlyEnumerable_]])
An analogue of [_map_ method][Array map] of Array prototype.
Returns the map that is the result of the application of callback to values
in all own properties of _self_ (or only enumerable own properties
if _onlyEnumerable_ is truthy).
Callback is passed _value_, _key_ and _self_ and should return value that will be
included in the map. Property descriptors of the returned map will have the same
values of properties _enumerable_, _configurable_ and _writable_ as the original map.
If _thisArg_ is set it will be the context (the value of _this_) in _callback_.
This method should not be used with arrays, it will include _length_ property
in iteration.
To map array-like objects use:
```javascript
var result = Array.prototype.map.call(arguments, callback, thisArg);
```
Array functions
---------------
Functions that Array [implements natively][Array methods] are not included.
#### __appendArray__ (_self_, _arrayToAppend_)
Appends _arrayToAppend_ to the end of array _self_ in place (can be an instance
of Array or array-like object).
Changes the value of _self_ (it uses Array.prototype.splice) and returns the new
value of _self_.
TODO: test
#### __prependArray__ (_self_, _arrayToPrepend_)
Appends _arrayToPrepend_ to the beginning of array _self_ in place (can be an instance of
Array or array-like object).
Changes the value of _self_ (it uses Array.prototype.splice) and returns the new
value of _self_.
TODO: test
#### __toArray__ (_arrayLike_)
Returns new array created from array like object (e.g., _arguments_ pseudo-array).
String functions
----------------
#### __firstUpperCase__ (_str_)
Returns string with the first character changed to upper case.
#### __firstLowerCase__ (_str_)
Returns string with the first character changed to lower case.
[Array methods]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods
[Array forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
[Array map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
* [__String functions__](http://mailonline.github.io/proto/string.js.html)
* [firstUpperCase](http://mailonline.github.io/proto/string.js.html#firstUpperCase)
* [firstLowerCase](http://mailonline.github.io/proto/string.js.html#firstLowerCase)

@@ -6,5 +6,27 @@ 'use strict';

function throwError() { throw new Error(); }
function doNothing() {}
function perfTest(func1, func2, times) {
// remove return to run performance tests
return;
times = times || 100000;
var time1 = time(func1);
var time2 = time(func2);
// change cnsl to console and uncomment to run test
// cnsl.log('time1:', time1, 'time2:', time2, 'diff: func1 is ', time1 / time2, 'times slower (if < 1 - faster)');
function time(func) {
var start = Date.now()
, i = times;
while (i--)
func();
return Date.now() - start;
}
}
describe('proto object library', function() {

@@ -102,2 +124,23 @@ it('should define extendProto function', function() {

it('should allow extend to be used as method of wrapped object', function() {
var obj = { prop1: 1 };
var obj2 = { prop2: 2 };
_(obj).extend(obj2);
assert.equal(obj.prop2, 2 , 'properties should be copied');
});
it('should allow extend chaining', function() {
var obj = { prop1: 1 };
var obj2 = { prop2: 2 };
var obj3 = { prop3: 3 };
_(obj).extend(obj2).extend(obj3);
assert.deepEqual(obj, { prop1: 1, prop2: 2, prop3: 3 }, 'properties should be copied');
});
it('should define deepExtend', function() {

@@ -428,2 +471,39 @@ var obj = {

it('should allow chaining of eachKey and mapKeys functions', function() {
var self = {
a: 1,
b: 2
};
function mapCallback(value) {
return value + 'test'
}
function eachCallback(value, key, obj) {
obj[key] = value * 10;
}
var result = _(self)
.eachKey(eachCallback)
.mapKeys(mapCallback)
._();
assert.deepEqual(result, { a: '10test', b: '20test' });
perfTest(
function(){
var result = _(self)
.eachKey(eachCallback)
.mapKeys(mapCallback)
._();
},
function() {
_.eachKey(self, eachCallback);
var result = _.mapKeys(self, mapCallback);
},
20000
);
});

@@ -464,2 +544,76 @@ it('should define appendArray function', function() {

it('should allow toArray, appendArray and prependArray chaining', function() {
var arrLike = { 0: 3, 1: 4, 2: 5, length: 3 };
var arr = _(arrLike)
.toArray()
.prependArray([1, 2])
.appendArray([6, 7, 8])
._();
assert(Array.isArray(arr), 'should be real array');
assert.deepEqual(arr, [1, 2, 3, 4, 5, 6, 7, 8],
'should add to the end and to the beginning of the array');
perfTest(
function(){
var arr = _(arrLike)
.toArray()
.prependArray([1, 2])
.appendArray([6, 7, 8])
._();
},
function() {
var arr = _.toArray(arrLike);
_.prependArray(arr, [1, 2]);
_.appendArray(arr, [6, 7, 8]);
}
);
});
it('should allow chaining of Proto functions together with native array methods', function() {
var myMap = {
prop0: 0,
prop1: 1,
prop2: 2,
prop3: 3
};
var newMap = {}
var result = _(myMap)
.allKeys()
.map(function(prop) { return prop + '_test'; })
.appendArray(['prop4', 'prop5'])
.filter(function(prop) { return prop != 'prop1_test'; })
.slice(1)
.object()
.mapKeys(function(value, key) { return key + '_test2' })
._();
assert.deepEqual(result, {
prop2_test: 'prop2_test_test2',
prop3_test: 'prop3_test_test2',
prop4: 'prop4_test2',
prop5: 'prop5_test2',
});
// perfTest(
// function(){
// var arr = _(arrLike)
// .toArray()
// .prependArray([1, 2])
// .appendArray([6, 7, 8])
// ._();
// },
// function() {
// var arr = _.toArray(arrLike);
// _.prependArray(arr, [1, 2]);
// _.appendArray(arr, [6, 7, 8]);
// }
// );
});
it('should define firstUpperCase function', function() {

@@ -481,2 +635,124 @@ var upper = 'UPPERCASE'

});
it('should define partial function', function() {
function testFunc(a,b,c) {
return a + b + c;
}
var testPartial = _.partial(testFunc, 'my ');
assert.equal(testFunc('my ', 'partial ', 'function'),
testPartial('partial ', 'function'));
var testPartial2 = _.partial(testFunc, 'my ', 'partial ');
assert.equal(testFunc('my ', 'partial ', 'function'),
testPartial2('function'));
});
it('should define memoize function', function() {
var called = 0;
function factorial(x) {
called++;
return x <= 0 ? 1 : x * fastFactorial(x-1);
}
var fastFactorial = _.memoize(factorial, undefined, 11);
var fact10 = factorial(10);
assert.equal(fastFactorial(10), fact10, 'should return the same result');
called = 0;
assert.equal(fastFactorial(10), fact10, 'should return the same result when called second time');
assert.equal(called, 0, 'should take the value from cache without calling original function');
assert.equal(fastFactorial(11), fact10 * 11, 'should return correct result');
assert.equal(called, 1, 'should be called with new value');
called = 0;
assert.equal(fastFactorial(11), fact10 * 11, 'should return correct result');
assert.equal(called, 0, 'should not be called with old value');
called = 0;
assert.equal(fastFactorial(0), 1, 'should return correct result');
assert.equal(called, 1, 'should be called again as the first key will be pushed out of cache');
function testFunc(a, b) {
called += 1;
return a + b;
}
function hashFunc (a, b) {
return a + b;
}
var memoTestFunc = _.memoize(testFunc, hashFunc);
var result = testFunc(10, 20);
assert.equal(memoTestFunc(10, 20), result);
called = 0;
assert.equal(memoTestFunc(10, 20), result);
assert.equal(called, 0, 'should not be called with same hash');
});
it('should allow chaining of partial and memoize', function() {
var called = 0;
function testFunc(a, b) {
called++;
return a + b;
}
var myFunc = _(testFunc).partial('my ').memoize()._();
assert.equal(testFunc('my ', 'function'),
myFunc('function'));
called = 0;
assert.equal(myFunc('function'), 'my function');
assert.equal(called, 0, 'value should be taken from cache');
perfTest(
function(){
var myFunc = _(testFunc).partial('my ').memoize()._();
},
function() {
var myFunc = _.partial(testFunc, 'my ')
myFunc = _.memoize(myFunc);
}
);
});
it('should define object function', function() {
var arr = ['a', 'b', 'c'];
assert.deepEqual(_.object(arr), {a: undefined, b: undefined, c: undefined});
assert.deepEqual(_.object(arr, 1), {a: 1, b: 1, c: 1});
assert.deepEqual(_.object(arr, [1, 2, 3]), {a: 1, b: 2, c: 3});
});
it('should define mapToObject function', function() {
var arr = ['a', 'b', 'c'];
var thisArg = {};
function callback(value, index, array) {
assert.equal(array, arr);
assert.equal(this, thisArg);
return value + index;
}
var result = _.mapToObject(arr, callback, thisArg);
assert.deepEqual(result, { a: 'a0', b: 'b1', c: 'c2' });
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc