Browse Source

Merge pull request #1238 from gormster/1237-list-expose-builtin-array-methods

Allow access to original Array.prototype methods on List prefixed with $
master
Ulrich-Matthias Schäfer 8 months ago
parent
commit
82778b7200
No account linked to committer's email address
2 changed files with 34 additions and 0 deletions
  1. 29
    0
      spec/spec/types/List.js
  2. 5
    0
      src/types/List.js

+ 29
- 0
spec/spec/types/List.js View File

@@ -73,6 +73,35 @@ describe('List.js', () => {
delete List.prototype.fooBar
})

it('keeps Array prototype names prefixed with $', () => {
// We're picking a function that we know isn't part of core svg.js
// If we implement an 'unshift' function at some point, change this to something else
if (List.prototype.hasOwnProperty('unshift')) {
fail('List.unshift is already a function - change this test to use a different name!');
return;
}

List.extend([ 'unshift' ])
expect(new List().unshift).toEqual(any(Function))
expect(new List().$unshift).toEqual(Array.prototype.unshift)

// Check that it works!
const sourceArray = [
{ 'unshift': () => 1 },
{ 'unshift': () => 2 },
{ 'unshift': () => 3 }
];
const list = new List(sourceArray)

expect(list).toEqual(sourceArray)
expect(list.unshift(0)).toEqual([1,2,3])

expect(list.$unshift(0)).toEqual(4)
expect(list).toEqual([0].concat(sourceArray))

delete List.prototype.unshift;
});

it('skips reserved names', () => {
const { constructor, each, toArray } = List.prototype
List.extend(['constructor', 'each', 'toArray'])

+ 5
- 0
src/types/List.js View File

@@ -47,6 +47,11 @@ List.extend = function (methods) {
// Don't add private methods
if (name[0] === '_') return obj

// Allow access to original Array methods through a prefix
if (name in Array.prototype) {
obj['$' + name] = Array.prototype[name]
}

// Relay every call to each()
obj[name] = function (...attrs) {
return this.each(name, ...attrs)

Loading…
Cancel
Save