Skip to content

Commit

Permalink
Decompose makeGetIndexFunction.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Mar 18, 2017
1 parent 0515084 commit a632931
Showing 1 changed file with 42 additions and 38 deletions.
80 changes: 42 additions & 38 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,44 +33,7 @@ function encode(value) {

function toTable(value) {
var values = [];
var indexMap = typeof Map === "function" && new Map;

function getIndex(value) {
switch (typeof value) {
case "undefined":
return UNDEFINED_INDEX;

case "number":
if (isNaN(value)) {
return NAN_INDEX;
}

if (! isFinite(value)) {
return value < 0 ? NEG_INF_INDEX : POS_INF_INDEX;
}

// fall through...
}

var index;

if (indexMap) {
// If we have Map, use it instead of values.indexOf to accelerate
// object lookups.
index = indexMap.get(value);
if (typeof index === "undefined") {
index = values.push(value) - 1;
indexMap.set(value, index);
}
} else {
index = values.indexOf(value);
if (index < 0) {
index = values.push(value) - 1;
}
}

return index;
}
var getIndex = makeGetIndexFunction(values);

function copy(value) {
var result = value;
Expand Down Expand Up @@ -150,6 +113,47 @@ function isPlainObject(value) {
return false;
}

function makeGetIndexFunction(values) {
var indexMap = typeof Map === "function" && new Map;

return function getIndex(value) {
switch (typeof value) {
case "undefined":
return UNDEFINED_INDEX;

case "number":
if (isNaN(value)) {
return NAN_INDEX;
}

if (! isFinite(value)) {
return value < 0 ? NEG_INF_INDEX : POS_INF_INDEX;
}

// fall through...
}

var index;

if (indexMap) {
// If we have Map, use it instead of values.indexOf to accelerate
// object lookups.
index = indexMap.get(value);
if (typeof index === "undefined") {
index = values.push(value) - 1;
indexMap.set(value, index);
}
} else {
index = values.indexOf(value);
if (index < 0) {
index = values.push(value) - 1;
}
}

return index;
};
}

exports.decode = exports.parse =
function decode(encoding) {
return fromTable(JSON.parse(encoding));
Expand Down

0 comments on commit a632931

Please sign in to comment.