Last active
August 29, 2015 14:07
-
-
Save a14n/2bc9d2d0be9e5e6b1592 to your computer and use it in GitHub Desktop.
List JsInterface over JsArray
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
import 'dart:collection'; | |
import 'package:js/js.dart'; | |
abstract class JsList<E> extends JsInterface with ListMixin<E> { | |
JsObject _js; | |
factory JsList() => new JsListImpl(); | |
JsList.created(JsObject o) : _js = o, super.created(o); | |
// method to implement for ListMixin | |
@override int get length => _js['length']; | |
@override void set length(int length) { _js['length'] = length; } | |
@override E operator [](index) { | |
if (index is int && (index < 0 || index >= this.length)) { | |
throw new RangeError.value(index); | |
} | |
return toDart(_js[index]); | |
} | |
@override void operator []=(int index, E value) { | |
if (index < 0 || index >= this.length) { | |
throw new RangeError.value(index); | |
} | |
_js[index] = toJs(value); | |
} | |
// overriden methods for better performance | |
@override void add(E value) { _js.callMethod('push', [toJs(value)]); } | |
@override void addAll(Iterable<E> iterable) { | |
_js.callMethod('push', iterable.map(toJs).toList()); | |
} | |
@override void sort([int compare(E a, E b)]) { | |
final sortedList = toList()..sort(compare); | |
setRange(0, sortedList.length, sortedList); | |
} | |
@override void insert(int index, E element) { | |
_js.callMethod('splice', [index, 0, toJs(element)]); | |
} | |
@override E removeAt(int index) { | |
if (index < 0 || index >= this.length) throw new RangeError.value(index); | |
return toDart(_js.callMethod('splice', [index, 1])[0]); | |
} | |
@override E removeLast() => toDart(_js.callMethod('pop')); | |
@override void setRange(int start, int length, List<E> from, | |
[int startFrom = 0]) { | |
final args = [start, length]; | |
for(int i = startFrom; i < startFrom + length; i++) { | |
args.add(toJs(from[i])); | |
} | |
_js.callMethod('splice', args); | |
} | |
@override void removeRange(int start, int end) { | |
_js.callMethod('splice', [start, end - start]); | |
} | |
} | |
@JsProxy(constructor: 'Array') | |
class JsListImpl extends JsList { | |
factory JsListImpl() => new JsInterface(JsListImpl, []); | |
JsListImpl.created(JsObject o) : super.created(o); | |
noSuchMethod(i) => super.noSuchMethod(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment