Created
January 12, 2012 14:01
-
-
Save teramako/1600667 to your computer and use it in GitHub Desktop.
グローバルにあるArrayを汚さずにprototype拡張などを施したArrayを生成する
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
// Copyright (c) 2012 by teramako <teramako.at.gmail.com> | |
// | |
// This work is licensed for reuse under an MIT license. Details are | |
// given in the License.txt file included with this file. | |
const EXPORTED_SYMBOLS = [ "Array" ]; | |
const bind = Function.prototype.bind, | |
uncurryThis = bind.bind(bind.call), | |
ArrayDescriptors = { | |
isinstance: { | |
value: function isinstance (obj) { | |
return obj instanceof Array; | |
}, | |
}, | |
toObject: { | |
value: function toObject() { | |
let obj = {}; | |
this.forEach(function ([k, v]) { obj[k] = v; }); | |
return obj; | |
} | |
}, | |
compact: { | |
value: function compact () { | |
return this.reduce(function(results, item) { | |
item != null && results.push(item); | |
return results; | |
}, []); | |
}, | |
}, | |
flatten: { | |
value: function flatten () { | |
return Array.prototype.concat.apply([], this); | |
}, | |
}, | |
itervalues: { | |
value: function itervalues () { | |
for (let i = 0, len = this.length; i < len; ++i) { | |
yield this[i]; | |
} | |
} | |
}, | |
iteritems: { | |
value: function iteritems() { | |
for (let i = 0, len = this.length; i < len; ++i) { | |
yield [i, this[i]]; | |
} | |
} | |
}, | |
uniq: { | |
value: function uniq () { | |
return this.reduce(function(results, item) { | |
results.indexOf(item) === -1 && results.push(item); | |
return results; | |
}, []); | |
}, | |
}, | |
}; | |
Object.defineProperties(Array.prototype, ArrayDescriptors); | |
var originalArray = Array; | |
Array = function Array (array) { | |
return originalArray.slice(array); | |
}; | |
Array.prototype = originalArray.prototype; | |
for (let [, key] in Iterator(Object.getOwnPropertyNames(originalArray))) { | |
if (typeof originalArray[key] === "function") { | |
Object.defineProperty(Array, key, Object.getOwnPropertyDescriptor(originalArray, key)); | |
} | |
} | |
for (let [key, desc] in Iterator(ArrayDescriptors)) { | |
Object.defineProperty(Array, key, { | |
value: uncurryThis(desc.value), | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment