Last active
August 29, 2015 14:27
-
-
Save larryprice/26b5641e4dc5eef84b7f to your computer and use it in GitHub Desktop.
Quick and dirty "blind" implementation of the functionality found at https://github.com/trevorparscal/more-underscore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = { | |
objectify: function (arr) { | |
var o = {}, | |
vals = arguments['0']; | |
for (var i = 1; i < arguments.length; ++i) { | |
if (i > vals.length) break; | |
o[arguments[i.toString()]] = vals[i - 1]; | |
} | |
return o; | |
}, | |
traverse: function (value, path, steps) { | |
if (!value || value.length === 0) return null; | |
value = value[path[0]]; | |
if (path.length === 1) { | |
return value; | |
} else { | |
return this.traverse(value, path.slice(1, path.length), steps); | |
} | |
}, | |
inject: function (arr, offset, items) { | |
// concats items to parameter list to get around | |
// array flattening problems | |
// WARNING: this could go past the js arguments length limit | |
// but i don't care for this sample code | |
// NOTE: i had to look up the answer to this one | |
// to find a better way to do it in-place | |
arr.splice.apply(arr, [offset, 0].concat(items)); | |
}, | |
extendClass: function (dst, src) { | |
dst.prototype = Object.create(src.prototype); | |
} | |
} | |
function testExtend() { | |
// Define parent class | |
function Foo() {} | |
Foo.prototype.x = function () {} | |
Foo.prototype.y = function () {} | |
// Define child class | |
function Bar() { | |
Foo.call(this); | |
} | |
Foo.prototype.y = "y"; | |
// Extend prototype | |
_.extendClass(Bar, Foo); | |
if (Bar.prototype.x === undefined) { | |
console.log("Extend failed: property 'x' not included"); | |
} | |
if (Bar.prototype.y !== "y") { | |
console.log("Extend failed: property 'x' not included"); | |
} | |
} | |
function testObjectify() { | |
var res = _.objectify([1, 2], 'a', 'b'), | |
exp = { | |
'a': 1, | |
'b': 2 | |
}; | |
if (JSON.stringify(res) !== JSON.stringify(exp)) { | |
console.log("Objectify failed:", res, "not equal", exp) | |
} | |
} | |
function testTraverse() { | |
var res = _.traverse({ | |
'a': ['b', 'c', { | |
'd': 'test' | |
}] | |
}, ['a', 2, 'd']), | |
exp = 'test'; | |
if (JSON.stringify(res) !== JSON.stringify(exp)) { | |
console.log("Traverse failed:", res, "not equal", exp) | |
} | |
} | |
function testInject() { | |
var arr = [0, 1, 2, 3], | |
exp = [0, 1, 'a', 'b', 'c', 2, 3]; | |
_.inject(arr, 2, ['a', 'b', 'c']); | |
if (JSON.stringify(arr) !== JSON.stringify(exp)) { | |
console.log("Traverse failed:", arr, "not equal", exp); | |
} | |
} | |
testObjectify(); | |
testTraverse(); | |
testInject(); | |
testExtend(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment