문제

As js is REALLY flexible language I always wondered if it's possible to create custom data type. Finally I've decided to try to create one. I'm not talking about simple class, rather about something what will behave more like js natives. I'm going to create range data type. Math range like (2.5;9] or (-Infinity;5). Also supporting sums of ranges (2;7] u (9;27). It'd allow to easily create iterators eg 2-8 with 0.25 step. I'd like it to support regular js syntax eg. for... in, or length property calculeted basing on step property.

sadly I've noticed that _iterator_ is supported only in ff but still it should be possible to prepare iterator by making other properties not enumerable.

I know about:

-Object.create/defineProperties
-getters/setters
-use strict (to maximize performance)
-_iterator_ (actually unsupported)

is there anything else that could be usefull?

Atm. I'd do it this way:

I'd create some hidden vars in local scope to precompute iterators after every change of step and store ranges. To make both completly invisible to user. All properties wouldn't be enumerable except steps - theese would be added with iterator recomputing. So simple range [2;7] with step 2 would look like:

local scope:
ranges:[[2;7]] // more arrays if it'd be sum
iterator:[2,4,6]
//other internal variables

not enumerable:
array: // returns copy of iterator using getter
//some other useful properties

enumerable:
0:2
1:4
2:6

Is it good idea, or there are other more proper ways to do it? Would it be possible to allow this class to use operators like +-?

도움이 되었습니까?

해결책

In JavaScript (ed. 5), one

  • cannot create custom grammar syntax or literal forms;
  • cannot overload operators

However, many "custom data types" have been created; feel free to create another. For instance, jQuery (manipulate sequences of DOM elements), moment.js (a Date replacement) and big.js (a "big number" type with operations) are all "custom data types" - albeit methods substitute as operators.

Otherwise, not really sure where the rest of the question is going .. except closed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top