MCPcopy Create free account
hub / github.com/bitpay/bitcore-message / arrayIndexOf

Function arrayIndexOf

bitcore-message.js:1007–1061  ·  view source on GitHub ↗
(arr, val, byteOffset, encoding, dir)

Source from the content-addressed store, hash-verified

1005}
1006
1007function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1008 var indexSize = 1
1009 var arrLength = arr.length
1010 var valLength = val.length
1011
1012 if (encoding !== undefined) {
1013 encoding = String(encoding).toLowerCase()
1014 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1015 encoding === 'utf16le' || encoding === 'utf-16le') {
1016 if (arr.length < 2 || val.length < 2) {
1017 return -1
1018 }
1019 indexSize = 2
1020 arrLength /= 2
1021 valLength /= 2
1022 byteOffset /= 2
1023 }
1024 }
1025
1026 function read (buf, i) {
1027 if (indexSize === 1) {
1028 return buf[i]
1029 } else {
1030 return buf.readUInt16BE(i * indexSize)
1031 }
1032 }
1033
1034 var i
1035 if (dir) {
1036 var foundIndex = -1
1037 for (i = byteOffset; i < arrLength; i++) {
1038 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1039 if (foundIndex === -1) foundIndex = i
1040 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1041 } else {
1042 if (foundIndex !== -1) i -= i - foundIndex
1043 foundIndex = -1
1044 }
1045 }
1046 } else {
1047 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1048 for (i = byteOffset; i >= 0; i--) {
1049 var found = true
1050 for (var j = 0; j < valLength; j++) {
1051 if (read(arr, i + j) !== read(val, j)) {
1052 found = false
1053 break
1054 }
1055 }
1056 if (found) return i
1057 }
1058 }
1059
1060 return -1
1061}
1062
1063Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1064 return this.indexOf(val, byteOffset, encoding) !== -1

Callers 1

bidirectionalIndexOfFunction · 0.85

Calls 1

readFunction · 0.85

Tested by

no test coverage detected